[ACCEPTED]-Why is my file not being returned by a GET request from my Web API function?-asp.net-web-api

Accepted answer
Score: 40

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");
}
Score: 4

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

More Related questions