为什么我的文件没有被我的Web API函数的GET请求返回?

时间:2022-10-24 22:39:33

I have a function accessible through my REST API, configured with ASP.NET Web API 2.1, that should return an image to the caller. For testing purposes, I just have it returning a sample image I have stored on my local machine right now. Here is the method:

我有一个函数可以通过我的REST API访问,配置ASP.NET Web API 2.1,应该将图像返回给调用者。出于测试目的,我只是让它返回我现在存储在本地计算机上的示例图像。这是方法:

public IHttpActionResult GetImage()
        {
            FileStream fileStream = new FileStream("C:/img/hello.jpg", FileMode.Open);
            HttpContent content = new StreamContent(fileStream);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
            content.Headers.ContentLength = fileStream.Length;
            return Ok(content);
         }

When this method gets called, I am not getting an image back at all. Here is the response I am receiving:

调用此方法时,我根本无法获取图像。以下是我收到的回复:

{"Headers":[{"Key":"Content-Type","Value":["image/jpeg"]},{"Key":"Content-Length","Value":["30399"]}]}

{ “接头”:[{ “密钥”: “内容类型”, “值”:[ “图像/ JPEG”]},{ “密钥”: “内容长度”, “值”:[ “30399”] }]}

Why am I not getting the image data back as part of the request? How can that be resolved?

为什么我没有将图像数据作为请求的一部分返回?怎么解决这个问题?

4 个解决方案

#1


24  

One possibility is to write a custom IHttpActionResult to handle your images:

一种可能性是编写自定义IHttpActionResult来处理您的图像:

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 your Web API controller action:

您可以在Web API控制器操作中使用:

public IHttpActionResult GetImage()
{
    return new FileResult(@"C:\\img\\hello.jpg", "image/jpeg");
}

#2


4  

Adding to what @Darin mentions, the Ok<T>(T content) helper which you are using actually returns a OkNegotiatedContentResult<T>, which as the name indicates runs content negotiation. Since you do not want content negotiation in this case, you need to create a custom action result.

除了@Darin提到的,你正在使用的Ok (T内容)帮助器实际上返回一个OkNegotiatedContentResult ,其名称表示运行内容协商。由于您不希望在这种情况下进行内容协商,因此您需要创建自定义操作结果。

Following is one sample of how you can do that: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/ActionResults/ActionResults/Results/OkFileDownloadResult.cs

以下是如何做到这一点的一个示例:http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/ActionResults/ActionResults/Results/OkFileDownloadResult.cs

#3


-1  

You can download your file by following code:

您可以通过以下代码下载您的文件:

    HttpResponse response = HttpContext.Current.Response; 
    response.Clear();
    response.Buffer = false;
    response.BufferOutput = false;
    response.Charset = "UTF-8";
    response.ContentEncoding = System.Text.Encoding.UTF8;           
    response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
    response.Write(excelXml);
    response.Flush();
    response.End();
    HttpContext.Current.Response.End();

#4


-1  

You can use following code for download the file from web api :

您可以使用以下代码从web api下载文件:

 HttpResponseMessage objResponse = Request.CreateResponse(HttpStatusCode.OK);               
 objResponse.Content = new StreamContent(new FileStream(HttpContext.Current.Server.MapPath("~/FolderName/" + FileName), FileMode.Open, FileAccess.Read));
 objResponse.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
 objResponse.Content.Headers.ContentDisposition.FileName = FileName;
 return objResponse;

#1


24  

One possibility is to write a custom IHttpActionResult to handle your images:

一种可能性是编写自定义IHttpActionResult来处理您的图像:

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 your Web API controller action:

您可以在Web API控制器操作中使用:

public IHttpActionResult GetImage()
{
    return new FileResult(@"C:\\img\\hello.jpg", "image/jpeg");
}

#2


4  

Adding to what @Darin mentions, the Ok<T>(T content) helper which you are using actually returns a OkNegotiatedContentResult<T>, which as the name indicates runs content negotiation. Since you do not want content negotiation in this case, you need to create a custom action result.

除了@Darin提到的,你正在使用的Ok (T内容)帮助器实际上返回一个OkNegotiatedContentResult ,其名称表示运行内容协商。由于您不希望在这种情况下进行内容协商,因此您需要创建自定义操作结果。

Following is one sample of how you can do that: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/ActionResults/ActionResults/Results/OkFileDownloadResult.cs

以下是如何做到这一点的一个示例:http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/ActionResults/ActionResults/Results/OkFileDownloadResult.cs

#3


-1  

You can download your file by following code:

您可以通过以下代码下载您的文件:

    HttpResponse response = HttpContext.Current.Response; 
    response.Clear();
    response.Buffer = false;
    response.BufferOutput = false;
    response.Charset = "UTF-8";
    response.ContentEncoding = System.Text.Encoding.UTF8;           
    response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
    response.Write(excelXml);
    response.Flush();
    response.End();
    HttpContext.Current.Response.End();

#4


-1  

You can use following code for download the file from web api :

您可以使用以下代码从web api下载文件:

 HttpResponseMessage objResponse = Request.CreateResponse(HttpStatusCode.OK);               
 objResponse.Content = new StreamContent(new FileStream(HttpContext.Current.Server.MapPath("~/FolderName/" + FileName), FileMode.Open, FileAccess.Read));
 objResponse.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
 objResponse.Content.Headers.ContentDisposition.FileName = FileName;
 return objResponse;