This, modified to return InternalServerError, is what my team uses in a public application, where all non-approved requests are handled by this Controller:
public class ErrorController : ApiController
{
[HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs("PATCH")]
public HttpResponseMessage HandleErrors()
{
HttpResponseMessage message = new HttpResponseMessage();
message.Content = new StringContent("<html><body><div>This is a custom message that will be displayed to the user in HTML format</div></body></html>");
message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
message.StatusCode = HttpStatusCode.InternalServerError;
return message;
}
}
Apart from this, we use a custom DefaultHttpControllerSelector and a custom ApiControllerActionSelector where the request that ask for unknown controllers and actions are retrieved by the ErrorController.
EDIT: Adding another sample, this is how you could return a generic error message, supposing that the Action (function) you want to call returns a IHttpActionResult
, and that you just want to return information on what happened:
return InternalServerError(ex);
Another sample, this is a little more complex than the previous one, but provides you with ways to send the details that you want, in the format you want:
public class SomethingFailedResult : IHttpActionResult
{
private HttpControllerContext _Context { get; set; }
private string _Message { get; set; }
public SomethingFailedResult(HttpControllerContext context, string message)
{
_Context = context;
_Message = message;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_Context.Request.CreateResponse(HttpStatusCode.InternalServerError,
_Message, "someMediaType"));
}
}
You would then create a helper method in your Controller, like this:
private SomethingFailedResult SomethingFailed(string contents, HttpControllerContext context)
{
return new ExpectionFailedResult(contents, context);
}