我在MVC应用程序中有一个帖子控制器返回此响应:
return new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent("test")
};
当我使用以下代码点击帖子网址时:
using (WebClient client = new WebClient())
{
string result = client.UploadString(url, content);
}
结果包含此回复:
StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Content-Type: text/plain; charset=utf-8 }
为什么没有"#34;测试"出现在内容之后:?
谢谢!
答案 0 :(得分:1)
您不应该从ASP.NET MVC操作返回HttpResponseMessage
。在这种情况下,你会得到像这样的凌乱回应:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRHJvcGJveFxwcm9nXFN0YWNrT3ZlcmZsb3dcZG90TmV0XE12Y0FwcGxpY2F0aW9u?=
X-Powered-By: ASP.NET
Date: Sun, 04 Feb 2018 10:18:38 GMT
Content-Length: 154
StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}
如您所见,实际上您在响应正文中获得了200个HTTP响应,其中包含HttpResponseMessage
个详细信息。这个凌乱的正文内容是您反序列化为result
变量的内容。
ASP.NET MVC操作应该返回从System.Web.Mvc.ActionResult
派生的类的实例。不幸的是,没有内置的动作结果允许设置返回状态代码和正文内容。
有ContentResult
类允许设置状态代码为200的返回字符串内容。还有HttpStatusCodeResult
允许设置任意状态代码,但响应正文将为空。
但是您可以使用可设置的状态代码和响应正文来实现自定义操作结果。为简单起见,您可以将其基于ContentResult
类。这是一个示例:
public class ContentResultEx : ContentResult
{
private readonly HttpStatusCode statusCode;
public ContentResultEx(HttpStatusCode statusCode, string message)
{
this.statusCode = statusCode;
Content = message;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
base.ExecuteResult(context);
HttpResponseBase response = context.HttpContext.Response;
response.StatusCode = (int)statusCode;
}
}
行动看起来像:
public ActionResult SomeAction()
{
return new ContentResultEx(HttpStatusCode.Accepted, "test");
}
另一种可能的解决方法是将控制器从MVC更改为WEB API控制器。要做到这一点 - 只需将控制器的基类从System.Web.Mvc.Controller
更改为System.Web.Http.ApiController
即可。在这种情况下,您可以在答案中返回HttpResponseMessage
。
在这两种情况下,您都将获得正确的HTTP响应,其中202状态代码和正文中的字符串:
HTTP/1.1 202 Accepted
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRHJvcGJveFxwcm9nXFN0YWNrT3ZlcmZsb3dcZG90TmV0XE12Y0FwcGxpY2F0aW9u?=
X-Powered-By: ASP.NET
Date: Sun, 04 Feb 2018 10:35:24 GMT
Content-Length: 4
test