繁体   English   中英

ASP.NET Web Api 2自定义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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM