【发布时间】:2020-11-20 14:11:25
【问题描述】:
问题:
由于某种原因,启用 CORS 时,Access-Control-Allow-Origin 标头未包含在响应中。
错误:
从 'https://.../api/endpoints/some-path' 访问 XMLHttpRequest 来源“https://some.site.com”已被 CORS 政策阻止: 对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin' 标头出现在请求的 资源。
配置 (.NET MVC 5)
web.config 标头:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Web API 配置:
config.EnableCors();
API 端点:
[RoutePrefix("api/endpoints")]
[EnableCors(origins: "https://some.site.com", headers: "*", methods: "*")]
public class MyApiController : ApiController
{
[HttpPost]
[Route("some-path")]
[EnableCors(origins: "https://some.site.com", headers: "*", methods: "*")]
public ResponseModel GetSomeResponse(DataModel model) { ... }
}
global.asax.cs
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
HttpContext.Current.Response.Flush();
}
我可以成功让应用程序返回该标头的唯一方法是将其作为自定义标头明确包含在 web.config 中:
<add name="Access-Control-Allow-Origin" value="https://some.site.com" />
【问题讨论】:
标签: c# asp.net-mvc api