使用WebInvoke在WCF Web Api中POST数据

时间:2011-07-10 11:42:32

标签: wcf rest wcf-web-api

我最近开始使用WCF WebApi来创建REST api。我跟踪了CodePlex上的样本以及Alex Zeitler的articles series

我尝试创建一个通过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标头字符。   参数名称:name'。请参阅服务器日志以获取更多详例外   堆栈跟踪是:

     

at System.Net.WebHeaderCollection.CheckBadChars(String name,Boolean   isHeaderValue)在System.Net.WebHeaderCollection.Add(String name,   字符串值)   System.Collections.Specialized.NameValueCollection.Add(NameValueCollection中   猫   System.ServiceModel.Activation.HostedHttpContext.HostedRequestContainer.System.ServiceModel.Channels.HttpRequestMessageProperty.IHttpHeaderProvider.CopyHeaders(WebHeaderCollection   标题)   System.ServiceModel.Channels.HttpRequestMessageProperty.get_Headers()   在   Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.ConfigureRequestMessage(消息   消息)   F:\ 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   请求)

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:5)

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

相关问题