具有如下定义的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
标头)。如何实现?
答案 0 :(得分:0)
在回复内容上设置内容类型。
private HttpResponseMessage GetExceptionalResponse(Exception ex) {
return new HttpResponseMessage {
Content = new StringContent(ex.Message, System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.InternalServerError
};
}