Search code examples
wcfhttp-status-code-401

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)
{
}

Solution

  • 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.