【问题标题】:CORS preflighting to WebAPI2 not returning correct headers对 WebAPI2 的 CORS 预检未返回正确的标头
【发布时间】:2016-11-01 17:27:57
【问题描述】:

我已经解决了几天的 CORS 问题,但我陷入了困境。我有一个 Angular 应用程序试图对 Json 数据进行简单的 HTTP 发布。

我已经按照此处描述的路线:ASP.NET Web API - CORS Support in ASP.NET Web API 2 使用自定义工厂,并且我已将 web.config 设置为:

    <handlers>
      <remove name="WebDAV"/>
      <remove name="OPTIONSVerbHandler"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>

我的 $http 后调用:

            var serviceEndpoint = "https://mybox/ourservices/myservices/1.0.0.1/api/process";

        var requestData ={'FirstName':'Nick','LastName':'Jacobs'};

        $http({
            method: "POST",
            url: serviceEndpoint,
            withCredentials: true,
            data: requestData,
            headers: {
                'Content-Type': 'application/json',
                'Accept':'application/json'
            }
        })
        .success(function (data, status, headers, config) {
            // I need to pick off the user name from the JSON that's returned.
            console.log(data);
            deferred.resolve(data);
        })
        .error(function (data, status) {
            deferred.reject(data);
        });

问题是,我看到了对服务器的飞行前请求,它传递了我的来源,并要求提供适当的标头,但我没有收到任何 CORS 响应标头。如果我进入 web.config 并添加允许的方法,我确实看到它回来了,但是由于我使用 withCredentials 那么我不能使用通配符来源响应标头,我希望工厂描述在上面的 MSDN 文档中将解决我的问题。

任何想法我缺少什么?

谢谢大家!

【问题讨论】:

  • 跟踪显示该请求甚至没有进入我的代码。它正在进入我的服务器。 (Win10 上的所有完整 IIS)。

标签: angularjs cors


【解决方案1】:

您需要在 web api 应用程序中配置 CORS。 CORS 有一个 nuget 包,基本上它是 web api 控制器中的一个属性和 web api 配置类中的一行配置,例如 config.EnableCors()。不需要任何角度配置。提示

MenusItemController.cs

[RoutePrefix("api/menus")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MenuItemsController : ApiController
{
    [Route("")]
    public IHttpActionResult Post()
    {
        return Ok(new
        {
            Result = "post menus"
        });
    }

    [Route("")]
    public IHttpActionResult Get()
    {
        return Ok(new
        {
            Result = "get menus"
        });
    }
}

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
}

Nuget 包

  • Microsoft.AspNet.WebApi.Cors
  • Microsoft.Owin.Cors
  • Microsoft.AspNet.Cors

我发布了我的应用并且运行良好。我没有做任何配置或角度请求参数。尝试在此处获取或发布:http://www.blocodecodigo.com.br/api/menus

【讨论】:

  • 还有比 config.EnableCors() 和 [EnableCors()] 属性更多的东西吗?我们沿着 MSDN 文章中的路线走,这样我们就可以有一个动态的来源.....
猜你喜欢
  • 2017-10-08
  • 2013-08-06
  • 2017-12-21
  • 2016-04-28
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 2017-01-01
  • 2014-08-17
相关资源
最近更新 更多