[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 { #region 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
}