I have a OWIN middleware class to do some authentication based on some custom tokens. All works fine. However I would like to return a useful error response to the client. My reasoning is that if the client asked for a 'application/json' response and they are expecting a serialize object, then that's what they should get, even if it is a 401 status code.
Here is the Invoke section of my middleware:
public override async Task Invoke(IOwinContext context)
{
try
{
this.DoAuthorization(context);
await this.Next.Invoke(context);
}
catch (UnauthorizedAccessException ex)
{
this.GenerateErrorResult(context, HttpStatusCode.Unauthorized, this.ExceptionToString(ex));
}
catch (Exception ex)
{
this.GenerateErrorResult(context, HttpStatusCode.InternalServerError, this.ExceptionToString(ex));
}
}
private void GenerateErrorResult(IOwinContext context, HttpStatusCode code, string errorMessage)
{
var result = new Result { Status = Result.EStatus.Error, ErrorText = errorMessage };
context.Response.StatusCode = (int)code;
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(result));
}
This all works fine, however:
- is this the 'correct' way?
- what if the client asks for 'application/xml', which obviously Web API is quite capable of supporting
Is there a better way to return a custom response object ('Result' in my case) that is serialized as the client would expect?