[ACCEPTED]-Why is my file not being returned by a GET request from my Web API function?-asp.net-web-api
Accepted answer
One possibility is to write a custom IHttpActionResult
to 2 handle your images:
public class FileResult : IHttpActionResult
{
private readonly string filePath;
private readonly string contentType;
public FileResult(string filePath, string contentType = null)
{
this.filePath = filePath;
this.contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(filePath))
};
var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}, cancellationToken);
}
}
that you could use in 1 your Web API controller action:
public IHttpActionResult GetImage()
{
return new FileResult(@"C:\\img\\hello.jpg", "image/jpeg");
}
Adding to what @Darin mentions, the Ok<T>(T content)
helper 6 which you are using actually returns a OkNegotiatedContentResult<T>
, which 5 as the name indicates runs content negotiation. Since 4 you do not want content negotiation in this 3 case, you need to create a custom action 2 result.
Following is one sample of how you 1 can do that: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/ActionResults/ActionResults/Results/OkFileDownloadResult.cs
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.