使用WebInvoke在WCF WebApi中POST数据

Mah*_*deh 1 rest wcf wcf-web-api

我最近开始使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的实体:

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
    public bool IsValidated { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Content-Type: application/json
Accept: application/json
{"Username": "mahdi", "Password":"123"}
Host: localhost:8181
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

服务器遇到处理请求的错误.异常消息是"指定的值具有无效的HTTP标头字符.参数名称:name'.请参阅服务器日志以获取更多详 异常堆栈跟踪是:

在System.Net.WebHeaderCollection.CheckBadChars(字符串名称,布尔isHeaderValue)在System.Net.WebHeaderCollection.Add(字符串名称,字符串值)System.Collections.Specialized.NameValueCollection.Add(NameValueCollection中c)中在System.ServiceModel.Activation位于F的Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.ConfigureRequestMessage(消息消息)中的System.ServiceModel.Channels.HttpRequestMessageProperty.get_Headers()处的.HostedHttpContext.HostedRequestContainer.System.ServiceModel.Channels.HttpRequestMessageProperty.IHttpHeaderProvider.CopyHeaders(WebHeaderCollection标头) :\的CodePlex\WCF\HTTP\SRC\Microsoft.ApplicationServer.Http \微软\ ApplicationServer的\ HTTP \频道\ HttpMessageEncodingRequestContext.cs:线222在Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.get_RequestMessage()在F:\ CodePlex上\ WCF\HTTP\SRC\Microsoft.ApplicationServer.Http \微软\ ApplicationServer的\ HTTP \电视\ HttpMessageEncodingRequestContext 的.cs:线54在System.ServiceModel.Dispatcher.ChannelHandler.EnsureChannelAndEndpoint(RequestContext的请求)在System.ServiceModel.Dispatcher.ChannelHandler.TryRetrievingInstanceContext(RequestContext的请求)

知道为什么会这样吗?

Dar*_*ler 5

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