【发布时间】: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