I created a custom Result I use in the Web API Controller actions where I return a custom 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
.
This however works when I return 200 OK.
Is there something I am doing wrong?
Try to set
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
in web.config. PassThrough option - leaves the response untouched if an existing response exists. ( more about httperrors )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.