Add Header to WCF Service to authenticate requests in ASP.Net

arjunsingh
 
on May 28, 2015 05:34 AM
3202 Views

I want to add header in my web service so that it is not misused. How can i achieve it.

My webservice template Iservice.cs

 

 [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getallchapters")]
    List<wsGetAllChapters> GetAllChapters();

 

I am calling it from Service.cs

 

public class Service : IService
{
    public List<wsGetAllChapters> GetAllChapters()
    {

        DataClassesDataContext dc = new DataClassesDataContext();

        List<wsGetAllChapters> results = new List<wsGetAllChapters>();

        foreach (Chapter ch in dc.Chapters)
        {
            results.Add(new wsGetAllChapters()
                {
                    Chapter_Id = ch.Chapter_Id,
                    Chapter_Name = ch.Chapter_Name.TrimEnd().TrimStart(),
                    Chapter_CreatedDate = Convert.ToString(ch.Chapter_CreatedDate),
                    Chapter_Description = ch.Chapter_Description.TrimEnd().TrimStart(),
                    Chapter_English_Name = ch.Chapter_English_Name.TrimEnd().TrimStart(),
                    Chapter_Number = ch.Chapter_Number,
                    Chapter_UpdatedDate = Convert.ToString(ch.Chapter_UpdatedDate),
                    Chapter_Number_Verses = ch.Chapter_Number_Verses,
                });

        } return results;
    }
    }

I am getting where i add header

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunsingh
 
on May 29, 2015 03:09 AM

 

public class SaasServiceMessageInspector : System.ServiceModel.Dispatcher.IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
        HttpRequestMessageProperty requestMessage = request.Properties["httpRequest"] as HttpRequestMessageProperty;
        if (request == null)
        {
            throw new InvalidOperationException("HttpRequestMessageProperty 'httpRequest' property not found !");
        }
        if (requestMessage.Headers["Header"] != "Value")
        {
            throw new WebFaultException<string>("That Was not Expected", HttpStatusCode.Forbidden);
        }




        return instanceContext;
    }
    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationstate)
    {

    }

}