[英]ASP.NET Web Api 2 Custom HttpResponseMessage
I created a custom Result I use in the Web API Controller actions where I return a custom async Task<IHttpActionResult>
. 我创建了在Web API Controller操作中使用的自定义结果,在该操作中返回自定义
async Task<IHttpActionResult>
。
public class CustomResult<T> : NegotiatedContentResult<T>
{
public CustomResult(HttpStatusCode statusCode, T content, ApiController controller)
: base(statusCode, content, controller)
{
}
public CustomResult(HttpStatusCode statusCode, T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
: base(statusCode, content, contentNegotiator, request, formatters) { }
public override async Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
{
HttpResponseMessage response = await base.ExecuteAsync(cancellationToken);
return response;
}
}
And basically in my action I return it like this: 基本上,在我的操作中,我将其返回为:
public async Task<IHttpActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return new CustomResult<string>(HttpStatusCode.BadRequest,"Model is invalid", this);
}
else
{
return new CustomResult<string>(HttpStatusCode.Ok,"Model is valid", this);
}
}
The problem is the custom message I want to return. 问题是我要返回的自定义消息。 It doesn't work!
它不起作用! If the model is invalid I always get the 400 Bad Request and the custom message:
"The remote server returned the following error while establishing a connection - 'Bad Request'
, instead of getting 400 Bad Request and my custom message Model is invalid
. 如果模型无效,我总是会收到400 Bad Request和自定义消息:
"The remote server returned the following error while establishing a connection - 'Bad Request'
,而不是得到400 Bad Request且我的自定义消息Model is invalid
。
This however works when I return 200 OK. 但是,当我返回200 OK时,此方法有效。
Is there something I am doing wrong? 我做错什么了吗?
Try to set 尝试设定
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
in web.config. 在web.config中。 PassThrough option - leaves the response untouched if an existing response exists.
PassThrough选项-如果存在现有响应,则使响应保持不变。 ( more about httperrors )
( 有关httperrors的更多信息 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.