2009-09-07 55 views
3

我有一个Windows服务托管的WCF服务。 我添加了一个webHttpBinding与webHttp的行为,每当我发送一个GET请求我得到http 200这是我想要的,问题是我得到一个HTTP 405,每当我发送一个HEAD请求。如何让WCF的webHttp行为接受HEAD动词?

有没有办法让它返回http 200也HEAD? 这甚至可能吗?

编辑:那就是经营合同:

[OperationContract] 
    [WebGet(UriTemplate = "MyUri")] 
    Stream MyContract(); 
+0

你能后的经营合同的HEAD动词吗? – 2009-09-07 07:16:26

+0

[OperationContract] [WebGet(UriTemplate =“MyUri”)] Stream MyContract(); – 2009-09-07 08:03:04

+3

3年多后这仍然是一个问题吗?我需要一个解决方案。 – 2013-01-08 19:03:25

回答

3
[ServiceContract] 
public interface IService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate="/data")] 
    string GetData(); 
} 

public class Service : IService 
{ 
    #region IService Members 

    public string GetData() 
    { 
     return "Hello"; 

    } 

    #endregion 
} 

public class Program 
{ 
    static void Main(string[] args) 
    { 
     WebHttpBinding binding = new WebHttpBinding(); 
     WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:9876/MyService")); 
     host.AddServiceEndpoint(typeof(IService), binding, "http://localhost:9876/MyService"); 
     host.Open(); 
     Console.Read(); 

    } 
} 

上面的代码工作正常。在HEAD请求中我得到了405(方法不允许)。我使用的程序集版本是System.ServiceModel.Web,Version = 3.5.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35。

实际上,据我所知,没有直接的方法允许它。但是你可以尝试类似下面的解决方案。但是这必须为每个需要GET和HEAD的方法完成,这使得它成为一个没有这么完美的解决方案..

[ServiceContract] 
public interface IService 
{ 
    [OperationContract] 

    [WebInvoke(Method = "*", UriTemplate = "/data")]   
    string GetData(); 
} 

公共类服务:IService { #地区IService成员

public string GetData() 
    { 
     HttpRequestMessageProperty request = 
      System.ServiceModel.OperationContext.Current.IncomingMessageProperties["httpRequest"] as HttpRequestMessageProperty; 

     if (request != null) 
     { 
      if (request.Method != "GET" || request.Method != "HEAD") 
      { 
       //Return a 405 here. 
      } 
     } 

     return "Hello"; 

    } 

    #endregion 
} 
+0

我想我的标题是误导性的,我想为HEAD请求以及GET获得200。 – 2009-09-07 09:10:23

+1

是的Prashanth在解释选项方面做了很多工作。但这个问题并没有解决。没有理由不能让头部使用web服务(这是一个标准动词)。猜猜我会继续挖掘一种方式来让WCF正确响应HEAD请求。 – 2011-09-08 01:59:35

1

听起来像是在服务(甚至框架)一个严重的错误。在HTTP/1.1中对HEAD的支持绝不是可选的。