WCF REST Service returns HTTP 400 Bad Request

2019-07-17 06:18发布

I've been trying to create a simple WCF RESTful web service, but it seems to work only in SOAP mode. I'm hosting my service with the local IIS.

It looks really standard:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    Guid Login(string username, string password);
...

and:

public class MyService : IMyService
{
    [WebGet(UriTemplate = "login?user={user}&password={password}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    public Guid Login(string username, string password)
    {
        return Guid.Empty;
    }

I also included the behavior in the config file and was using it in:

<endpoint address="" binding="webHttpBinding" contract="MyService" behaviorConfiguration="webHttp"/>

according to all of the examples I know...

Now the thing is when invoking the login from a stub client which uses ServiceReference, it looks just fine in Fiddler, but it is SOAPy. From some reason I cannot invoke my service in a RESTy way, even the /help seems to return a 400 Bad Request. (I'm invoking http://localhost:8080/MyService.svc/help or /login etc.)

What is preventing the REST to take action? Thanks in advance :)

Edit: I found an answer.

It turns out one must define Routings...

After adding this to Global.asax :

    protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.Add(new ServiceRoute("MyService",
           new WebServiceHostFactory(), typeof(MyService)));
    }

It went through just fine.

Plus I earned that the ".svc" is now not part of the URL.

2条回答
欢心
2楼-- · 2019-07-17 06:52

Your code looks good to me. Can you try couple of things

[OperationContract]
[WebGet(UriTemplate = "/Login/{username}/{password}", ResponseFormat = WebMessageFormat.Xml)]
Guid Login(string username, string password);

At the same time please remove the WebGet attribute from MyService.Login function.

-OR-

Put this block in your web.config under system.web

<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

Hope this helps.

查看更多
SAY GOODBYE
3楼-- · 2019-07-17 06:54

I had the same issue the reason was my posting xml had the below on top

<?xml version="1.0" encoding="utf-16"?>

I removed it and it just worked!

查看更多
登录 后发表回答