![](/img/trans.png)
[英]ASP.NET Web API Conditionally return HttpResponseMessage
[英]ASP.NET Web Api 2 Custom HttpResponseMessage
我創建了在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;
}
}
基本上,在我的操作中,我將其返回為:
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);
}
}
問題是我要返回的自定義消息。 它不起作用! 如果模型無效,我總是會收到400 Bad Request和自定義消息: "The remote server returned the following error while establishing a connection - 'Bad Request'
,而不是得到400 Bad Request且我的自定義消息Model is invalid
。
但是,當我返回200 OK時,此方法有效。
我做錯什么了嗎?
嘗試設定
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
在web.config中。 PassThrough選項-如果存在現有響應,則使響應保持不變。 ( 有關httperrors的更多信息 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.