1

I'm writing a Web API in using the MVC 4 Web API framework. I'm using BASIC authentication with a custom authentication message handler inheriting from DelegatingHandler.

Everything is working peachy, except my error handling.

I'm using the Web API as a wrapper over an existing authentication mechanism and an exception is thrown when the user's password is expired. Within the API action methods, I am able to handle this easily by throwing an HTTPResponseException and I get a tidy little json object such as below:

{
"Message": "Password is expired."
}

If I try this same approach in my Auth Message Handler, I get all the nasty .NET response output.

<html>
<head>
    <title>Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.</title>
    <style>
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
... you get the idea ...

I think I'm close... in SendAsync

catch (Exception ex)
{
    var response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
    response.Headers.Add("WWW-Authenticate", "Basic realm=\"myrealm\"");
}

Here, perhaps if I can somehow get a Task<HttpResponseMessage> from my response object to return, I think I might be ok.

Basically my question is "How should exception handling really be done so that I am able to return a nice json/xml object to the user?"

One more thing to note, this is .NET 4, not 4.5. I've seen a few examples using the await keyword, but that won't work in this scenario.

4

1 回答 1

2

You can wrap your response in a task:

catch (Exception)
{
    return Task<HttpResponseMessage>.Factory.StartNew(() =>
    {
        var response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
        response.Headers.Add("WWW-Authenticate", "Basic realm=\"myrealm\"");
        return response;
    });
}

return base.SendAsync(request, cancellationToken);
于 2013-04-16T23:58:24.063 回答