使用WebInvoke在WCF WebApi中发布数据

使用WebInvoke在WCF WebApi中发布数据,wcf,rest,wcf-web-api,Wcf,Rest,Wcf Web Api,我最近开始使用创建RESTAPI。我跟踪了CodePlex和Alex Zeitler提供的样本 我尝试创建一个通过POST接收数据的方法,如下所示: [ServiceContract] public class AuthenticateApi { [WebInvoke(UriTemplate = "", Method = "POST")] public HttpResponseMessage<LoginModel> Post(LoginModel loginMod

我最近开始使用创建RESTAPI。我跟踪了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);
    }
}
最后,这是我在Global.asax中的配置:

public static void RegisterRoutes(RouteCollection routes)
{
   routes.MapServiceRoute<AuthenticateApi>("login");
}
protected void Application_Start(object sender, EventArgs e)
{
   RegisterRoutes(RouteTable.Routes);
}
我收到以下错误消息:

服务器在处理请求时遇到错误。例外 “消息为”指定的值包含无效的HTTP头字符。 参数名称:name'。有关详细信息,请参阅服务器日志。例外 堆栈跟踪是:

在System.Net.WebHeaderCollection.CheckBadChars(字符串名,布尔值 isHeaderValue)在System.Net.WebHeaderCollection.Add(字符串名称, 字符串值)在 System.Collections.Specialized.NameValueCollection.Add(NameValueCollection c) 在 System.ServiceModel.Activation.HostedHttpContext.HostedRequestContainer.System.ServiceModel.Channel.HttpRequestMessageProperty.IHttpHeaderProvider.CopyHeaders(WebHeaderCollection 标题)在 System.ServiceModel.Channels.HttpRequestMessageProperty.get_Headers() 在 Microsoft.ApplicationServer.Http.Channel.HttpMessageEncodingRequestContext.ConfigureRequestMessage(消息 信息)在 F:\codeplex\wcf\Http\Src\Microsoft.ApplicationServer.Http\Microsoft\ApplicationServer\Http\Channels\HttpMessageEncodingRequestContext.cs:line 222 at Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.get_RequestMessage() 在里面 F:\codeplex\wcf\Http\Src\Microsoft.ApplicationServer.Http\Microsoft\ApplicationServer\Http\Channels\HttpMessageEncodingRequestContext.cs:line 54 at System.ServiceModel.Dispatcher.ChannelHandler.EnsureChannelAndEndpoint(RequestContext (请求)在 System.ServiceModel.Dispatcher.ChannelHandler.TryRetrievingInstanceContext(RequestContext 请求)


知道为什么会发生这种情况吗?

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

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

您在哪里传递JSON对象?从您的示例来看,它看起来像是在消息头中传递的。您到底在哪里传递JSON对象?从您的示例来看,它看起来像是在消息头中传递的。@Mahdi:如果您在Fiddler中打开请求生成器,则有一部分用于请求头和请求体@Mahdi:如果您在Fiddler中打开请求生成器,则会有一部分用于请求头和请求体!
public static void RegisterRoutes(RouteCollection routes)
{
   routes.MapServiceRoute<AuthenticateApi>("login");
}
protected void Application_Start(object sender, EventArgs e)
{
   RegisterRoutes(RouteTable.Routes);
}
Content-Type: application/json
Accept: application/json
{"Username": "mahdi", "Password":"123"}
Host: localhost:8181