ASP.NET Core Web API处理HttpResponseMessage类型返回值的问题

栏目: ASP.NET · 发布时间: 6年前

内容简介:ASP.NET Core Web API处理HttpResponseMessage类型返回值的问题

在将我们的 web api 从 .NET Framework 迁移至 .net core(asp.net core 1.1)之后,遇到一个问题。

之前返回值类型为 HttpResponseMessage 的 web api,比如:

[HttpGet]
public async Task<HttpResponseMessage> Get()
{
    return await _httpClient.GetAsync($"...");
}

(注:这个 web api 的用途是直接将 HttpClient 调用后端 web api 的结果返回给调用客户端)

原本会返回 json 格式的业务数据,现在返回的却是对 HttpResponseMessage 自己的 json 序列化数据:

{
  "version": {},
  "content": {},
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [],
  "requestMessage": {
    "version": {},
    "content": null,
    "method": { "method": "GET" },
    "requestUri": "",
    "headers": [],
    "properties": {}
  },
  "isSuccessStatusCode": true
}

驴头不对马嘴。

后来在 stackoverflow 上找到了解决方法 —— ASP.NET Core HTTPRequestMessage returns strange JSON message ,用回答中的方法成功解决了这个问题。

解决方法如下:

1)在 .csproj 中添加下面的配置,为了可以安装第2步中的 nuget 包(asp.net core 2.0不需要添加这个配置)

<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8</PackageTargetFallback>

2)安装 nuget 包 Microsoft.AspNetCore.Mvc.WebApiCompatShim

3)在 Startup -> ConfigureServices 中,在 AddMvc() 之后添加 AddWebApiConventions() 即可:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddWebApiConventions();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

jQuery in Action

jQuery in Action

Bear Bibeault、Yehuda Katz / Manning Publications / 2008-2-17 / USD 39.99

A good web development framework anticipates what you need to do and makes those tasks easier and more efficient; jQuery practically reads your mind. Developers of every stripe-hobbyists and professio......一起来看看 《jQuery in Action》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具