Nayan
Nayan

Reputation: 327

how to send status code as response for Unauthorized requests to WCF rest service

I am trying to develop a WCF rest servie which needs authorization using custom attribute.

I want to send the response as 401 status code if the authorization key is not valid in custom attribute which implements IOperationBehavior and IParameterInspector.

can any one tell me how to send the 401 status code as response from the custom attribute.

Here is the implementation

public class AuthorizationAttribute : Attribute,IOperationBehavior,
IParameterInspector
{

 #region IOperationBehavior Members 

 public void ApplyDispatchBehavior(OperationDescription operationDescription,
 System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
 {
  dispatchOperation.ParameterInspectors.Add(this);
 }  
 #endregion

 #region IParameterInspector Members

 public object BeforeCall(string operationName, object[] inputs)
 {          

  string publicKey =
  WebOperationContext.Current.IncomingRequest.Header["Authorization"];

   if (publicKey == "592F2D7E-5E9C-400D-B0AE-1C2603C34137")
   {

   } 
   else
   {
    // Here i would like to send the response back to client 
     with the status code       
   }

 }

 return null;

}

 #endregion

}


[Authorization]
public bool signin(string username, string password)
{
}

Upvotes: 1

Views: 4394

Answers (4)

Balaji Gunasekaran
Balaji Gunasekaran

Reputation: 435

If aspnetcompatibilityMode cannot be enabled in your WCF services, then you can do as below.

You have to intercept the message and set the status code in HttpResponseMessageProperty in the wcf message. I use a CustomErrorHandler for doing that and it works fine.


public class CustomErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
              fault.Properties[HttpResponseMessageProperty.Name] = new HttpResponseMessageProperty() 
              { 
                    StatusCode = statusCode 
              };
        }
    }

Below code is for injecting CustomErrorHandler into the ServiceBehavior.

public class CustomServiceBehaviour : IServiceBehavior
{
    ... other IServiceBehavior methods

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
        {
            channelDispatcher.ErrorHandlers.Add(new CustomErrorHandler());
        }
    }
}

Then in web.config use the serviceBehavior

<system.serviceModel>
    <extensions>
        <behaviorExtensions>
            <add name="CustomServiceBehavior" type="MyNamespace.CustomServiceBehavior, MyAssembly" />
        </behaviorExtensions>
    </extensions>
    <behaviors>
        <serviceBehaviors>
            <behavior name="CustomBehavior">
                <CustomServiceBehavior />
            </behavior>
      </serviceBehaviors>
    </behaviors>
    <service behaviorConfiguration="CustomBehavior" name="SomeService">
        <endpoint ..../>
    </service>
</system.serviceModel>

Upvotes: 0

tichra
tichra

Reputation: 553

public string CreateError(int code ,string description)
        {
            Context.Response.StatusCode = code;
            Context.Response.StatusDescription = description;
            Context.ApplicationInstance.CompleteRequest();
            return null;
        }

Then from your web service methods just use this to return errors example:

return CreateError(403, "Request denied by server");

Upvotes: 0

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16013

If you're using WCF Rest Starter kit you can also do:

throw new Microsoft.ServiceModel.Web.WebProtocolException(System.Net.HttpStatusCode.Unauthorized, "message", ex);

That method has some more overloads if you need.

Upvotes: 0

Richard Blewett
Richard Blewett

Reputation: 6109

Throw a WebFormatException

throw new WebFaultException(HttpStatusCode.Unauthorized);

Upvotes: 2

Related Questions