[英]Call WebAPI method from MVC4
我有一個MVC4 WebAPI
項目,並且有一個控制器FileController
,其中包含此Get方法:
public HttpResponseMessage Get(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File Name Not Specified");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = fileService.GetFileStream(id);
if (stream == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File Not Found");
}
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = id;
return response;
}
在轉到localhost:9586/File/myfile.mp3
的瀏覽器中,它正確地將文件作為附件分派,您可以保存它。 如果它是音頻文件,則可以從HTML5
音頻標簽流式傳輸它。
現在,我需要從MVC4
Web應用程序調用此WebAPI
方法,基本上將其包裝。 它來了:
public HttpResponseMessage DispatchFile(string id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8493/");
HttpResponseMessage response = client.GetAsync("api/File/"+id).Result;
return response;
}
轉到localhost:8493/File/DispatchFile/my.mp3
返回:
狀態碼:200,原因短語:“確定”,版本:1.1,內容:System.Net.Http.StreamContent,標題:{語法:no-cache連接:Close Cache-Control:no-cache日期:Thu,2013年9月5日15 :33:23 GMT服務器:ASP.NET服務器:開發服務器:Server / 10.0.0.0 X-AspNet版本:4.0.30319內容長度:13889內容處置:附件; filename = horse.ogg內容類型:application / octet-stream過期:-1}
因此,看起來內容確實是StreamContent,但它沒有將其作為可保存文件返回。 現在的問題是,如何在直接調用API時反映行為? 任何建議,不勝感激。
我相信在這里使用HttpClient.Result不是正確的方法。 我認為您可能需要使用'Content'屬性,然后調用ReadAsStreamAsync以獲取由WebAPI方法返回的文件流的句柄。 到那時,您應該能夠將此流寫入響應流,從而允許通過HTML5下載文件/音頻。
請參閱此處,以獲取使用HttpClient獲取文件的示例(鏈接顯示了如何處理大文件,但我相信您所需要使用的方法):
http://developer.greenbutton.com/downloading-large-files-with-the-net-httpclient/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.