【发布时间】:2014-12-03 13:26:34
【问题描述】:
当我通过使用计算机名称的 url 访问 ASP.net 自托管 Web api 2 时收到 400 bad request 错误。当我使用 localhost 时,它工作正常。
我知道这可以通过更新 applicationhost.config 来解决 IIS 托管站点的问题,但是如何在 web-api 2 中修复它?
【问题讨论】:
标签: asp.net-web-api self-hosting
当我通过使用计算机名称的 url 访问 ASP.net 自托管 Web api 2 时收到 400 bad request 错误。当我使用 localhost 时,它工作正常。
我知道这可以通过更新 applicationhost.config 来解决 IIS 托管站点的问题,但是如何在 web-api 2 中修复它?
【问题讨论】:
标签: asp.net-web-api self-hosting
这里的问题是Web API认为你是从不同的域访问它,这是默认不允许的。
这称为Cross-origin resource sharing (CORS)。
Web API 2.2 通过提供EnableCorsAttribute 可以轻松启用CORS。
基本用法
[EnableCors("*", "*", "*")]
public class ResourcesController : ApiController
{
...
属性定义
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)]
public EnableCorsAttribute(
string origins,
string headers,
string methods
)
您还需要从nuget 安装 CORS 包
Install-Package Microsoft.AspNet.WebApi.Cors
【讨论】:
No 'Access-Control-Allow-Origin' header is present on the requested resource. 或类似的东西有关,而不是 invalid host