2013-10-14 24 views
0

我想创建一个web服务。我成功地将HttpClient请求发送到Web服务并获得响应。如何阅读WebService发送HttpHeaders由HttpClient发送

我想要什么?

我发送一些HttpHeaders与POST请求像userAgent或任何CustomHeader。我想在webservice方法中读取标题。我不知道如何获取标题列表?

我在C#中创建了webservice。

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

回答

0

请尝试使用WebOperationContext.Current.IncomingRequest对象。

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"; 
        } 
       } 
     } 
+0

嗨感谢您的回复,但我越来越空ctx。我做错了什么。 –

+1

如果您使用WCF构建WebService,然后使用WebOperationContext.Current.IncomingRequest.Headers http://stackoverflow.com/questions/18877591/how-to-read-http-request-headers-in-a-wcf-web-服务 – mit

+0

非常感谢它的工作。你可以请编辑你的原始答案,以便我可以让你的答案正确:) –