Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top