我目前正在开发一个带有.NET Core Web App的API进行测试,我一直坚持这个。
实际上,我有这段代码:
namespace CoreWebApp.API.Admin
{
[Route("api/country")]
public class CountryController : Controller
{
// GET: api/country
[HttpGet]
public HttpResponseMessage Get()
{
List<Country> countries = Shared.Database.SqlAction.CountriesTable.GetCountries();
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(countries), Encoding.UTF8, "application/json") };
}
}
}
我要做的是返回HttpStatusCode
和HttpContent
。然后我应该在Postman上得到它:
[
{
"Name":"France"
},
{
"Name":"Germany"
},
{
"Name":"Spain"
},
....
]
StatusCode Ok 200
然而,我根本没有得到这个身体,我得到的是:
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"application/json; charset=utf-8"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true
}
我现在正在寻找一段时间,我仍然无法获取内容中的数据,我做错了什么?这是我的第一个.NET Core Api,如果你有一些建议,请随时给出任何建议:)
感谢您的帮助!
答案 0 :(得分:4)
Asp.net核心不再支持返回的HttpResponseMessage
类型
要解决您的问题,推荐的返回类型如下所示
[HttpGet]
public async Task<IActionResult> GeTask()
{
List<Country> countries = Shared.Database.SqlAction.CountriesTable.GetCountries();
return Ok(countries);
}
更多强> 这里完整标准.net中的ApiController如何看起来像
//
// Summary:
// Creates a System.Web.Http.Results.ResponseMessageResult with the specified response.
//
// Parameters:
// response:
// The HTTP response message.
//
// Returns:
// A System.Web.Http.Results.ResponseMessageResult for the specified response.
protected internal virtual ResponseMessageResult ResponseMessage(HttpResponseMessage response);
来自.net核心的控制器基类的源代码没有HttpResponseMessage