現在、WebAPI コントローラーを介して返されるファイルを強制的にダウンロードする方法を探しています。
http://www.shawnmclean.com/blog/2012/04/force-download-of-file-from-asp-net-webapi/を参照として使用していました。
私のクライアントでは、ajax GET 呼び出しを使用してオブジェクトの ID を送信し、ファイルをダウンロードしようとしています
exportList: (foo, callback) =>
path = '/api/export/id'
path = path.replace("id", foo.id)
$.ajax(
url: path,
dataType: 'text',
success: (data) =>
callback(data)
error: (data) =>
callback(false)
)
サーバー側では、上記の URI を以下のメソッドにルーティングしています
[AcceptVerbs("GET")]
public HttpResponseMessage ExportList(int id)
{
string file = fooService.ExportList(id);
if (file == null)
{
return Request.CreateResponse(HttpStatusCode.NoContent);
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(file);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "List.csv";
return result;
}
fooService.ExportList メソッドは、単純に csv 文字列を作成します。
要求がクライアントに返されるのを監視すると、応答には csv 文字列が含まれていますが、クライアントはそれをダウンロードするように求められたり、強制されたりしません。
これは正しい方法ですか?