如何让 WCF webHttp 行为接受 HEAD 动词?

Mei*_*lon 5 wcf http webhttpbinding webhttp

我有一个 WCF 服务托管在 Windows 服务中。我已经向它添加了一个具有 webHttp 行为的 webHttpBinding,每当我向它发送 GET 请求时,我都会得到 http 200,这正是我想要的,问题是每当我向它发送 HEAD 请求时,我都会得到一个 http 405。

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

编辑:那是操作合同:

    [OperationContract]
    [WebGet(UriTemplate = "MyUri")]
    Stream MyContract();
Run Code Online (Sandbox Code Playgroud)

Pra*_*nth 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();

    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常。我收到 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();
}
Run Code Online (Sandbox Code Playgroud)

公共类服务:IService { #region IService Members

    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
}
Run Code Online (Sandbox Code Playgroud)