WCF REST服务返回HTTP 400错误请求

时间:2012-01-09 11:54:51

标签: wcf rest bad-request

我一直在尝试创建一个简单的WCF RESTful Web服务,但它似乎只能在SOAP模式下工作。我正在使用本地IIS托管我的服务。

它看起来非常标准:

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

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;
    }

我还在配置文件中包含了行为,并在以下位置使用它:

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

根据我所知道的所有例子......

现在问题是当从使用ServiceReference的存根客户端调用登录时,它在Fiddler中看起来很好,但它是SOAPy。 由于某些原因,我无法以RESTy方式调用我的服务,即使/ help似乎返回400 Bad Request。 (我正在调用http://localhost:8080/MyService.svc/help或/ login等。)

什么阻止REST采取行动? 在此先感谢:)

编辑:我找到了答案。

事实证明必须定义 Routings ......

将此添加到Global.asax后:

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

它经历了很好。

另外,我认为“.svc”现在不属于URL。

2 个答案:

答案 0 :(得分:1)

您的代码对我来说很好。你可以尝试几件事吗

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

同时请从MyService.Login函数中删除WebGet属性。

-OR -

将此块放在system.web

下的web.config中
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

希望这有帮助。

答案 1 :(得分:1)

我有同样的问题 原因是我的帖子xml上面有以下

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

我删除它,它只是工作!

相关问题