5

I have a WCF service hosted in a Windows service. I've added to it a webHttpBinding with a webHttp behaviour and whenever I send it a GET request I get http 200 which is what I want, problem is I get an http 405 whenever I send it a HEAD request.

Is there a way to make it return http 200 also for HEAD? Is that even possible?

edit: that's the operation contract:

    [OperationContract]
    [WebGet(UriTemplate = "MyUri")]
    Stream MyContract();
Meidan Alon
  • 3,074
  • 7
  • 45
  • 63

2 Answers2

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

    }
}

The above code works fine. I get a 405 (Method not allowed) on HEAD request. The version of assembly I am using is System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.

Actually as far as I know there is no straight forward way of allowing it.However you could try something like the solution below..But this has to be done for each method that needs GET and HEAD, which makes it a not so elegant solution..

[ServiceContract]
public interface IService
{
    [OperationContract]

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

public class Service : 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
}
Prashanth
  • 2,404
  • 1
  • 17
  • 19
  • I guess my title was misleading, I want to get a 200 for a HEAD request as well as for a GET. – Meidan Alon Sep 07 '09 at 09:10
  • 1
    Yeah Prashanth has done a great job here of explaining options. But this question is in NO WAY solved. There's NO reason you shouldn't be able to get a HEAD to work with a webservice (it's a STANDARD verb). Guess I'll keep digging for a way to get WCF to respond correctly to HEAD requests. – Michael K. Campbell Sep 08 '11 at 01:59
1

Sounds like a serious bug in the service (or even the framework). Support for HEAD in HTTP/1.1 is in no way optional.

Julian Reschke
  • 40,156
  • 8
  • 95
  • 98