我有一个Windows服务托管的WCF服务。 我已经加入到它的WebHttpBinding与webHttp行为,每当我发送一个GET请求,我得到HTTP 200这是我想要的,问题是,我得到一个HTTP 405每当我发送一个HEAD请求。

有没有一种方法,使之返回HTTP 200也为HEAD? 是否可能?

编辑:这就是操作合同:

    [OperationContract]
    [WebGet(UriTemplate = "MyUri")]
    Stream MyContract();
有帮助吗?

解决方案

[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,版本= 3.5.0.0,文化=中性公钥= 31bf3856ad364e35。

其实,据我所知,让你it.However可以尝试类似的解决方案below..But这对每一个方法需要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
}

其他提示

听起来像在服务(或甚至框架)一个严重的错误。在HTTP / 1.1 HEAD支持不以任何方式是可选的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top