ASP.NET Core HTTPRequestMessage返回奇怪的JSON消息 [英] ASP.NET Core HTTPRequestMessage returns strange JSON message
问题描述
我目前正在使用ASP.NET Core RC2,但遇到了一些奇怪的结果。
所以我有一个具有以下功能的MVC控制器:
I am currently working with ASP.NET Core RC2 and I am running into some strange results. So I have an MVC controller with the following function:
public HttpResponseMessage Tunnel() {
var message = new HttpResponseMessage(HttpStatusCode.OK);
message.Content = new StringContent("blablabla", Encoding.UTF8);
message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
message.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue {
NoCache = true
};
return message;
}
如果我使用邮递员将此邮件(将Accept标头设置为纯文本)进行调用此响应:
If I call this with postman with an Accept header set to text plain I get this response:
{
"Version": {
"Major": 1,
"Minor": 1,
"Build": -1,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
},
"Content": {
"Headers": [
{
"Key": "Content-Type",
"Value": [
"text/plain"
]
}
]
},
"StatusCode": 200,
"ReasonPhrase": "OK",
"Headers": [
{
"Key": "Cache-Control",
"Value": [
"no-cache"
]
}
],
"RequestMessage": null,
"IsSuccessStatusCode": true
}
我真的不明白这是如何生成对上述控制器的响应。它基本上是整个消息本身的JSON序列化,并且绝不包含我要发送的 blablabla。
I really do not understand how this is the generated reponse to the above controller. It is basically a JSON serialization of the entire message itself and does in no way contain the "blablabla" I intended to send.
我获得所需结果的唯一方法是通过使我的控制器函数返回 string
而不是 HttpResponse
,但是我无法设置<$这样的标头c $ c> CacheControl
The only way I have gotten the desired result is by making my controller function return string
instead of HttpResponse
, but that way I am unable to set headers like CacheControl
所以我的问题是:为什么会得到这个奇怪的响应?对我来说,这似乎是非常奇怪的行为
So my question is: why do I get this strange response? It seems like very weird behaviour to me
推荐答案
根据本文,ASP.NET Core MVC不支持 HttpResponseMessage
-默认情况下是返回方法。
According to this article, ASP.NET Core MVC does not support HttpResponseMessage
-returning methods by default.
如果要继续使用它,可以使用WebApiCompatShim:
If you want to keep using it, you can, by using WebApiCompatShim:
- 将对
Microsoft.AspNetCore.Mvc.WebApiCompatShim
的引用添加到项目中。 / li>
- 在
ConfigureServices()
中进行配置:services.AddMvc()。AddWebApiConventions();
-
在
Configure()
中为其设置路由:
- Add reference to
Microsoft.AspNetCore.Mvc.WebApiCompatShim
to your project. - Configure it in
ConfigureServices()
:services.AddMvc().AddWebApiConventions();
Set up route for it in
Configure()
:
app.UseMvc(routes =>
{
routes.MapWebApiRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
这篇关于ASP.NET Core HTTPRequestMessage返回奇怪的JSON消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!