简体   繁体   中英

ASP.NET Web API handled exception return wrong status code

I have project using ASP.NET Web API 2.0 and have a method in this API throwing an exception:

    public void TestMethod()
    {
        throw new Exception("Error40001");
    }

When this exception is thrown I have made a handler to handle these sort of things:

public class APIExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var rm = Language.Error.ResourceManager;
        string message = rm.GetString(context.Exception.Message);
        string detailed = "";
        try
        {
            detailed = rm.GetString(context.Exception.Message + "Detailed");
        }
        catch
        {
            if (String.IsNullOrEmpty(detailed))
            {
                detailed = message;
            }
        }
        HttpStatusCode code = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), context.Exception.Message.Replace("Error", "").Substring(0, 3));

        context.Result = new ResponseMessageResult(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));
    }
}

public class ErrorInformation
{
    public string Message { get; set; }
    public string DetailedMessage { get; set; }
}

The problem I have is that when I receive this error back it is no longer the same status code that I set it to. The handler picks it up and creates a response message result with error code 400.

Here you see the result that is returned with status code 400

400 stts

But when I receive the error in the browser the status code has changed

Here you see the status code that is returned

cd chged

And the content

cntent

As can be seen in the last picture the content from the handled exception is at the start, but a default error message has been included and the status code has been overwritten.

The problem I am having is even if i remove the custom error messages from the webconfig the message is the same. Is this some default behavior that can be overridden? Am I missing something important?

Instead of setting context.Result use following code

throw new HttpResponseException(context.Request.CreateResponse(code,
            new ErrorInformation() { Message = message, DetailedMessage = detailed }));

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.

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