1

I have an operation handler that checks for authentication and throws an exception when authentication fails using

throw new WebFaultException(HttpStatusCode.Unauthorized); 

However this still returns a 404 Not Found status code to the client/test client.

This is my operation handler

public class AuthOperationHandler : HttpOperationHandler<HttpRequestMessage, HttpRequestMessage>
{
    RequireAuthorizationAttribute _authorizeAttribute;

    public AuthOperationHandler(RequireAuthorizationAttribute authorizeAttribute) : base("response")
    {
        _authorizeAttribute = authorizeAttribute;
    }

    protected override HttpRequestMessage OnHandle(HttpRequestMessage input)
    {
        IPrincipal user = Thread.CurrentPrincipal;

        if (!user.Identity.IsAuthenticated)
            throw new WebFaultException(HttpStatusCode.Unauthorized);

        if (_authorizeAttribute.Roles == null)
            return input;

        var roles = _authorizeAttribute.Roles.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

        if (roles.Any(role => user.IsInRole(role)))
            return input;

        throw new WebFaultException(HttpStatusCode.Unauthorized);
    }
}

Am I doing something wrong?

Stuart
  • 201
  • 1
  • 11

1 Answers1

1

I have good and bad news for you. The framework your are using has evolved into ASP.NET Web API. Unfortunately, OperationHandlers no longer exist. Their closest equivalent are ActionFilters.

Having said that, WCF Web API never supported throwing WebFaultException, that is a vestige of WCF's SOAP heritage. I think the exception was called HttpWebException, however, I never used it, I just set the status code on the response.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • That doesn't bode well, i was going to migrate my api (based on preview 6) to the beta tomorrow. I have an operation handler based validation handler :( – Antony Scott Feb 20 '12 at 19:48
  • @AntonyScott ActionFilters are capable of doing most of what you could do with OperationHandlers. – Darrel Miller Feb 20 '12 at 20:39
  • hmm okay. looks like I've got a bit of a rewrite tomorrow then :) – Antony Scott Feb 20 '12 at 21:01
  • I just saw a presentation from Scott Gu on Asp.Net WebApi and I will be stopping any further development in WCF WebApi anyway so this is affectively not an issue any more. I can just use the built in ActionFilters from MVC with the new WebApi, which is also a better solution as I am mainly an MVC guy, so smiles all round :) Also thanks for the info @DarrelMiller – Stuart Feb 21 '12 at 21:23