gpt4 book ai didi

c# - EnableCors 属性未向 API 响应添加 Access-Control-Allow-Origin

转载 作者:行者123 更新时间:2023-12-04 11:36:50 24 4
gpt4 key购买 nike

问题:
出于某种原因,启用 CORS 时,Access-Control-Allow-Origin响应中不包含 header 。
错误:

Access to XMLHttpRequest at 'https://.../api/endpoints/some-path' fromorigin 'https://some.site.com' has been blocked by CORS policy:Response to preflight request doesn't pass access control check: No'Access-Control-Allow-Origin' header is present on the requestedresource.


配置 (.NET MVC 5)
web.config header :
<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();
}
我可以成功让应用程序返回该 header 的唯一方法是将其作为自定义 header 显式包含在 中。 web.config :
<add name="Access-Control-Allow-Origin" value="https://some.site.com" />

最佳答案

添加与 HttpOptions 相同的方法 header 和相同的路由名称。浏览器将向您的 Controller 发送预检请求。这意味着 Options方法将被触发访问服务器的头信息。

[HttpOptions]
[Route("some-path")]
[EnableCors(origins: "https://some.site.com", headers: "*", methods: "*")]
public ResponseModel GetSomeResponse(DataModel model) { ... }

关于c# - EnableCors 属性未向 API 响应添加 Access-Control-Allow-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63179819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com