【问题标题】:web api 2 bad request when accessed the host using ip address使用 ip 地址访问主机时的 web api 2 错误请求
【发布时间】: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


    【解决方案1】:

    这里的问题是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
    

    【讨论】:

    • 但如果是这样的话,错误应该与 CORS No 'Access-Control-Allow-Origin' header is present on the requested resource. 或类似的东西有关,而不是 invalid host
    猜你喜欢
    • 2017-12-22
    • 1970-01-01
    • 2018-05-09
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多