0

I am trying to create a webservice. I am successfully able to send HttpClient Request to web service and getting response too.

What I want ?

I am sending some HttpHeaders with the POST request like userAgent, or any CustomHeader. That Header I want to read in webservice method. I don't know how to get Header list ?

I created webservice in C#.

   public class Service1 :IService1{   
           public string putData(Stream data)
            {
        string response = string.Empty;
        try
        {
            HttpContext ctx = HttpContext.Current;
            string headerValue = ctx.Request.Headers["tej"];              
            StreamReader reader = new StreamReader(data);
            string xmlString = reader.ReadToEnd();
            StringReader sr = new StringReader(xmlString);
            MySqlCommand cmd = new MySqlCommand();
            DataSet ds = new DataSet();

            ds.ReadXml(sr);
            //my logic here....

            return "Passed";
        }
        catch (Exception ex)
        {
           return "Failed";
        }
    }
}

 public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle =                 WebMessageBodyStyle.Wrapped, UriTemplate = "putdata")]
    string putData(Stream sDatabase); 
}
Tej Kiran
  • 2,218
  • 5
  • 21
  • 42

1 Answers1

0

Please try following using WebOperationContext.Current.IncomingRequest object.

public class Service1 :IService1
     {   
               public string putData(Stream data)
                {
                   try
                   {
                       //reading headers
                       IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
                       WebHeaderCollection headers = request.Headers;
                       foreach (string headerName in headers.AllKeys)
                       {
                            Console.WriteLine(headerName + ": " + headers[headerName]);
                       }

                       //---- rest of the code
                   }
                   catch (Exception ex)
                   {
                      return "Failed";
                   }
                }
      }
mit
  • 1,763
  • 4
  • 16
  • 27
  • Hi Thanks for reply, But I am getting null fro ctx. What I am doing wrong. – Tej Kiran Oct 14 '13 at 09:45
  • 1
    If you are using WCF to build WebService then use WebOperationContext.Current.IncomingRequest.Headers http://stackoverflow.com/questions/18877591/how-to-read-http-request-headers-in-a-wcf-web-service – mit Oct 14 '13 at 10:43
  • Thanks a lot its working. can you please edit your origin answer so that I can make your answer correct :) – Tej Kiran Oct 14 '13 at 11:24