【问题标题】:Using WebInvoke to POST data in WCF WebApi使用 WebInvoke 在 WCF WebApi 中发布数据
【发布时间】:2023-03-16 21:48:01
【问题描述】:

我最近开始使用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 标头字符。 参数名称:名称'。有关更多详细信息,请参阅服务器日志。例外 堆栈跟踪是:

在 System.Net.WebHeaderCollection.CheckBadChars(字符串名称,布尔值 isHeaderValue) 在 System.Net.WebHeaderCollection.Add(字符串名称, 字符串值)在 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\Microsoft\ApplicationServer\Http\Channels\HttpMessageEncodingRequestContext.cs:line 222 在 Microsoft.ApplicationServer.Http.Channels.HttpMessageEncodingRequestContext.get_RequestMessage() 在 F:\codeplex\wcf\Http\Src\Microsoft.ApplicationServer.Http\Microsoft\ApplicationServer\Http\Channels\HttpMessageEncodingRequestContext.cs:line 54 在 System.ServiceModel.Dispatcher.ChannelHandler.EnsureChannelAndEndpoint(RequestContext 请求)在 System.ServiceModel.Dispatcher.ChannelHandler.TryRetrievingInstanceContext(RequestContext 请求)

知道为什么会这样吗?

【问题讨论】:

  • 你到底在哪里传递那个 JSON 对象?从您的示例看来,您将其传递到消息头中。

标签: wcf rest wcf-web-api


【解决方案1】:

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

【讨论】:

  • @Mahdi:如果您在 Fiddler 中打开请求构建器,则请求标头和请求正文的部分!
猜你喜欢
  • 2011-10-14
  • 2017-06-05
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
相关资源
最近更新 更多