1

我最近开始使用WCF WebApi创建 REST api。我关注了 CodePlex 上提供的示例以及Alex Zeitler 的文章系列

我试图创建一个通过 POST 接受数据的方法,如下所示:

[ServiceContract]
public class AuthenticateApi
{
    [WebInvoke(UriTemplate = "", Method = "POST")]  
    public HttpResponseMessage<LoginModel> Post(LoginModel loginModel)
    {
        loginModel.IsValidated = true;
        return new HttpResponseMessage<LoginModel>(loginModel);
    }
}

这是我的实体:

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
    public bool IsValidated { get; set; }
}

最后这是我在 Global.asax 中的配置:

public static void RegisterRoutes(RouteCollection routes)
{
   routes.MapServiceRoute<AuthenticateApi>("login");
}
protected void Application_Start(object sender, EventArgs e)
{
   RegisterRoutes(RouteTable.Routes);
}

当我尝试以这种方式使用 Fiddler 发布内容时:

Content-Type: application/json
Accept: application/json
{"Username": "mahdi", "Password":"123"}
Host: localhost:8181

我收到以下错误消息:

服务器在处理请求时遇到错误。异常消息是“指定的值具有无效的 HTTP 标头字符。参数名称:名称'。有关更多详细信息,请参阅服务器日志。异常堆栈跟踪是:

在 System.Net.WebHeaderCollection.CheckBadChars(String name, Boolean isHeaderValue) 在 System.Net.WebHeaderCollection.Add(String name, String value) 在 System.Collections.Specialized.NameValueCollection.Add(NameValueCollection c) 在 System.ServiceModel.Activation .HostedHttpContext.HostedRequestContainer.System.ServiceModel.Channels.HttpRequestMessageProperty.IHttpHeaderProvider.CopyHeaders(WebHeaderCollection headers) at System.ServiceModel.Channels.HttpRequestMessageProperty.get_Headers() at Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.ConfigureRequestMessage(Message message) in F :\codeplex\wcf\Http\Src\Microsoft.ApplicationServer.Http\Microsoft\ApplicationServer\Http\Channels\HttpMessageEncodingRequestContext.cs:Microsoft.ApplicationServer.Http.Channels 的第 222 行。F:\codeplex\wcf\Http\Src\Microsoft.ApplicationServer.Http\Microsoft\ApplicationServer\Http\Channels\HttpMessageEncodingRequestContext.cs 中的 HttpMessageEncodingRequestContext.get_RequestMessage():System.ServiceModel.Dispatcher.ChannelHandler.EnsureChannelAndEndpoint 的第 54 行(RequestContext 请求) 在 System.ServiceModel.Dispatcher.ChannelHandler.TryRetrievingInstanceContext(RequestContext 请求)

知道为什么会这样吗?

4

1 回答 1

5

将 JSON 对象放在请求正文字段中,而不是放在标头中。

于 2011-07-10T12:37:20.947 回答