我目前正在使用ASP.NET Core RC2,我遇到了一些奇怪的结果.
所以我有一个具有以下功能的MVC控制器:
所以我有一个具有以下功能的MVC控制器:
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标题设置为text plain,我得到这个回应:
{
"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”.
我获得所需结果的唯一方法是通过使我的控制器函数返回字符串而不是HttpResponse,但是我无法设置头像CacheControl
所以我的问题是:为什么我得到这个奇怪的回应?对我来说似乎是非常奇怪的行为
解决方法
根据
this article,默认情况下,ASP.NET Core MVC不支持HttpResponseMessage返回方法.
如果你想继续使用它,你可以通过使用WebApiCompatShim:
>将Microsoft.AspNetCore.Mvc.WebApiCompatShim的引用添加到您的项目中.
>在ConfigureServices()中配置它:services.AddMvc().AddWebApiConventions();
>在Configure()中设置路由:
app.UseMvc(routes =>
{
routes.MapWebApiRoute(
name: "default",template: "{controller=Home}/{action=Index}/{id?}");
});