WCF REST Self-Hosted 400 Bad Request

久未见 提交于 2019-12-06 16:02:25

When you use the WebServiceHost, you typically don't need to add a service endpoint - it will add one with all behaviors required to make it a "Web HTTP" (a.k.a. REST) endpoint (i.e., an endpoint which doesn't use SOAP and you can easily consume with a tool such as Fiddler, which seems to be what you want). Also, Web HTTP endpoints aren't exposed in the WSDL, so you don't need to add the ServiceMetadataBehavior either.

Now for why it doesn't work - sending a GET request to http://localhost:8000/Test should work - and in the code below it does. Try running this code, and sending the request you were sending before with Fiddler, to see the difference. That should point out what the issue you have.

public class StackOverflow_15705744
{
    [ServiceContract]
    public interface IRestService
    {
        [OperationContract]
        [WebGet(UriTemplate = "Test")]
        bool Test();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class RestService : IRestService
    {
        public bool Test()
        {
            Debug.WriteLine("Test Called.");
            return true;
        }
    }

    public static void Test()
    {
        var baseAddress = new Uri("http://localhost:8000/");
        var host = new WebServiceHost(typeof(RestService), baseAddress);

        // host.AddServiceEndpoint(typeof(IRestService), new WSHttpBinding(), "RestService");

        // var smb = new ServiceMetadataBehavior();
        // smb.HttpGetEnabled = true;
        // host.Description.Behaviors.Add(smb);

        host.Open();

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress.ToString().TrimEnd('/') + "/Test"));

        Console.WriteLine("Service Running.  Press any key to stop.");
        Console.ReadKey();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!