我有一个 MVC 网络 API,带有名为 GetNames 的 GET 方法。
当我想从另一个网站的 AJAX 调用 myapi.com/controller/GetNames 时,出现 Access-Control-Allow-Origin
错误。
所以在我的 MVC Web API 代码中,
我在我的 WebApiConfig 中添加了这个:
config.EnableCors();
然后我将其添加到我的 Controller 方法中:
[HttpGet]
[EnableCors(origins: "http://mywebsite.net", headers: "*", methods: "*")]
public string GetNames(string requestKey)
如果很多网站都在调用这个方法怎么办?
我想允许许多来源,如果我可以允许所有来源,而不仅仅是定义的来源,那就更好了。
最佳答案
来自 EnableCorsAttribute
上的文档:
origins: Comma-separated list of origins that are allowed to access the resource. Use "*" to allow all.
因此对于来源列表,您的属性现在看起来像这样:
[EnableCors(origins: "http://site1.com,http://site2.com", headers: "*", methods: "*")]
或者对于所有来源都是这样:
[EnableCors(origins: "*", headers: "*", methods: "*")]
关于c# - 在 EnableCors() 中允许多个来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743879/