I have a custom ExceptionHandler
for my Web API:
public class GlobalExceptionHandler : ExceptionHandler
{
private class ErrorInformation
{
public string Message { get; set; }
public DateTime ErrorDate { get; set; }
}
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new ErrorInformation { Message = "We apologize but an unexpected error occurred. Please try again later.", ErrorDate = DateTime.UtcNow }));
}
}
Here is the controller code
[HttpPost]
public async Task<HttpResponseMessage> UserNameChange(UserNameChangeRequest updateUsersRequest)
{
throw new Exception("sdfsdf");
}
I am registering it like this
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.Converters.Add(new JsonStringEncoder());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
}
If I put a breakpoint, it gets hit just fine. But the output to the client is still HTML, not the expected JSON.
UPDATE: I added the following as a filter attribute, still same result. NO JSON just HTML error page public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext actionExecutedContext) {
var exceptionMessage = actionExecutedContext.Exception.InnerException?.Message ?? actionExecutedContext.Exception.Message;
var response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new { Message = exceptionMessage });
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.OK, new {ErrorMessage = actionExecutedContext.Exception.Message},
new JsonMediaTypeFormatter());
}
}
I created a new project, added my NewtonSoft JSON config and a customer ErrorAtribute, works as expected.
What in my project could be stopping the error from coming across as JSON? Even when I navigate in a browser to the API endpoint it shows as a generic HTML error but in the sample project with the same code it shows as JSON message I want???