【发布时间】:2017-10-22 06:34:40
【问题描述】:
我遇到了一个问题,我无法让 POST 内容在 Web API 中按预期工作。
按照教程,我应该能够在控制器中拥有如下所示的路由(表格 1):
[Route("my-post-method")]
public HttpResponseMessage MyPostMethod(MyModel model)
{
Request.CreateResponse(HttpStatus.OK, model.SomeNumber * 5);
}
但这不起作用。相反,我必须执行以下操作(表格 2):
[Route("my-post-method")]
public HttpResponseMessage MyPostMethod()
{
var text = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var model = JsonConvert.DeserializeObject<MyModel>(text);
Request.CreateResponse(HttpStatusCode.OK, model.SomeNumber * 5);
}
现在,我认为这与项目中的 CORS 设置有关,但我不确定。如果我尝试通过 Postman 请求表格 1,一切都会按预期工作。如果我尝试通过浏览器向表单 1 发出请求并且我没有设置 Content-Type 标头,我会在 POST 请求上收到不支持的媒体类型错误(这是我期望发生的),但是如果我设置Content-Type 标头到“application/json”,然后 Web API 在 OPTIONS 预检请求上返回 404 响应。此外,将 [FromBody] 属性添加到方法参数不会做任何事情。
Web.config 包含:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
启动配置类有:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
jsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.EnsureInitialized();
}
【问题讨论】:
-
不应该添加FromBody属性吗?
-
您提到了 forms,然后谈到了 Json。你想做什么?同时向我们展示您是如何尝试从浏览器中发布此模型的。
-
另外,从不在同一应用程序中为 this reason 启用两次 CORS。在
Web.config内的 Web Api OR 中启用它,而不是同时启用。 -
使用 EnableCors 属性装饰 Action 方法,并从 web.config 中删除 CORS 内容
标签: c# asp.net asp.net-web-api visual-studio-2013