AspNet.WebApi总是将我的错误响应转换为text / html

时间:2017-06-29 14:35:08

标签: c# asp.net-web-api exception-handling

具有如下定义的ExceptionFilter属性:

public class HandleExceptionsFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.Response = GetExceptionalResponse(context.Exception);

        base.OnException(context);
    }

    public override Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext,
        CancellationToken cancellationToken)
    {
        return
            Task.FromResult(GetExceptionalResponse(actionExecutedContext.Exception));
    }

    private HttpResponseMessage GetExceptionalResponse(Exception ex)
    {
        return new HttpResponseMessage
        {
            Content = new StringContent(ex.Message, System.Text.Encoding.UTF8, null),
            StatusCode = HttpStatusCode.InternalServerError
        };
    }
}

当异常发生时,我总是得到一堆html代码包装我的异常细节。我想要的是只将异常消息返回到前端(并发送text/plain Content-Type标头)。如何实现?

1 个答案:

答案 0 :(得分:0)

在回复内容上设置内容类型。

private HttpResponseMessage GetExceptionalResponse(Exception ex) {
    return new HttpResponseMessage {
        Content = new StringContent(ex.Message, System.Text.Encoding.UTF8, "text/plain"),
        StatusCode = HttpStatusCode.InternalServerError
    };
}