Asp.Net Core下HttpResponseMessage输出文件前端始终输出Json

今天有个场景需要webapi返回给客户端回应一个图片,以前的老套路不能用了。刚开始以为是需要使用“HttpResponseMessage“,直接使用HttpResponseMessage输出文件流

[HttpGet]
[Route("get")]
public HttpResponseMessage Get()
{
    string path = @"C:\Users\***\Desktop\img0a28a1cbc674acd370585883abba3172.jpg";
    HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
    var bytes = GetIMGbyte(path);
    message.Content = new ByteArrayContent(bytes);
    message.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
    message.Content.Headers.ContentLength = bytes.Length;
    return message;
}

当我在浏览器中调用此终结点时,.Net Core 下 Web API会将HttpResponseMessage的HTTP内容标头设置为,以JSON形式返回application/json

原因分析:

dnx或者是asp.net core的webapi里面,如果要返回一个图片,需要返回一个IActionResult类型的,因为这两个的框架把HttpResponseMessage 当成一个model来处理的,所以使用HttpResponseMessage 始终返回Json

{
  "version":{
    "major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1
  },
  "content":{
    "headers":[
      {"Key":"Content-Type","Value":["image/jpg"]},
      {"Key":"Content-Length","Value":["206371"]}
    ]
  },
  "statusCode":200,"reasonPhrase":"OK","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true
}

解决办法:

您可以使用以下方法返回FileResult:

1:返回FileContentResult

[HttpGet]
[Route("get2")]
public async Task<FileContentResult> GetFiel()
{
    string path = @"C:\Users\admin\Desktop\hk\img0a28a1cbc674acd370585883abba3172.jpg";
    var mimeType = "image/jpg";
    var bytes = GetIMGbyte(path);
    return new FileContentResult(bytes, mimeType){
        FileDownloadName = "1.jpg"
        //如果设置了FileDownloadName ,则浏览器会直接下载该文件,不设置则浏览器会直接显示图片
    };
}
private byte[] GetIMGbyte(string PicturePath)
{
    //将需要存储的图片读取为数据流
    FileStream fs = new FileStream(PicturePath, FileMode.Open, FileAccess.Read);           
    Byte[] btye2 = new byte[fs.Length];
    fs.Read(btye2, 0, Convert.ToInt32(fs.Length));
    fs.Close();
    return btye2;
}

2:返回FileStreamResult

[HttpGet]
[Route("get3")]
public async Task<FileStreamResult> GetFiel3()
{
    string path = @"C:\Users\admin\Desktop\hk\img0a28a1cbc674acd370585883abba3172.jpg";
    var stream = new FileStream(path, FileMode.Open);
    var mimeType = "image/jpg";          
    return new FileStreamResult(stream, mimeType) {
        FileDownloadName = "1.jpg"
        //如果设置了FileDownloadName ,则浏览器会直接下载该文件,不设置则浏览器会直接显示图片
    };
}

 

参考资料:Return file in ASP.Net Core Web API

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ASP.NET Core WebAPI 项目中,你可以通过使用 Model Binding 功能来解析 JSON 数据并将其转换为 User 类对象。以下是一个简单的示例代码: 首先,确保你的 User 类具有与 JSON 数据字段对应的属性。例如: ```csharp public class User { public string Name { get; set; } public int Age { get; set; } // 其他属性... } ``` 然后,在你的控制器中的相应方法中,使用 `[FromBody]` 特性将 JSON 数据绑定到 User 类对象上。例如: ```csharp [HttpPost] public IActionResult CreateUser([FromBody] User user) { // 这里的 user 参数将包含从请求中解析的 JSON 数据 // 执行其他操作,如保存到数据库 return Ok(); } ``` 在上述示例中,`CreateUser` 方法使用 `[FromBody]` 特性将请求的 JSON 数据绑定到名为 `user` 的 User 类对象上。你可以根据需要在该方法中执行相应的操作,比如将 user 对象保存到数据库中。 当发送 POST 请求时,确保请求的 Content-Type 设置为 `application/json`,并提供符合 User 类结构的 JSON 数据。例如: ```http POST /api/users HTTP/1.1 Content-Type: application/json { "Name": "John", "Age": 25 } ``` 这样,ASP.NET Core WebAPI 就会自动将请求中的 JSON 数据解析为 User 对象,并将其传递给 `CreateUser` 方法中的 user 参数。 注意:为了使 Model Binding 可以正常工作,你需要在 `Startup.cs` 文件中添加适当的配置。例如,在 `ConfigureServices` 方法中添加以下代码: ```csharp services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.PropertyNamingPolicy = null; }); ``` 这样,你就可以在 ASP.NET Core WebAPI 项目中成功解析 JSON 数据成 User 类,并进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胡老汉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值