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

标签 c# .net rest asp.net-web-api

我有一个可通过我的 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);
         }

调用此方法时,我根本没有取回图像。这是我收到的回复:

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

为什么我没有在请求中取回图像数据?如何解决?

最佳答案

一种可能性是编写自定义 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);
    }
}

您可以在 Web API Controller 操作中使用:

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

关于c# - 为什么我的文件没有被我的 Web API 函数的 GET 请求返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23768596/

相关文章:

c# - 编译特定版本的 DotNetOpenAuth 并进行小改动,签名问题

.net - jquery 类似 c#/.Net 中的扩展

java - Jersey Rest Service 中的多个 PUT 方法

java - Controller有很多@Autowired服务

c# - 什么开源 C# 库可以读/写微型 QR 码?

javascript - 通过 REST 使用 Web 服务,并使用完整的 JavaScript 进行身份验证

c# - 在不使用 app.config 的情况下添加连接字符串

c# - 如何在 2 个独立的 C# 程序之间进行事件驱动编程?

c# - 如果没有正确实现,像 IEnumerable 这样的接口(interface)如何工作?

c# - 日历粗体日期