Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

后端 未结 11 559
庸人自扰
庸人自扰 2020-11-27 11:06

I tried to follow the steps at http://enable-cors.org/server_aspnet.html to have my RESTful API (implemented with ASP.NET WebAPI2) work with cross origin requests (CORS Enab

11条回答
  •  悲哀的现实
    2020-11-27 11:57

    I've created a pared-down demo project for you.

    • Source: https://github.com/bigfont/webapi-cors
    • Api Link: https://cors-webapi.azurewebsites.net/api/values

    You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.

    Global.ascx

    All this does is call the WebApiConfig. It's nothing but code organization.

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }
    }
    

    WebApiConfig.cs

    The key method for your here is the EnableCrossSiteRequests method. This is all that you need to do. The EnableCorsAttribute is a globally scoped CORS attribute.

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            EnableCrossSiteRequests(config);
            AddRoutes(config);
        }
    
        private static void AddRoutes(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "api/{controller}/"
            );
        }
    
        private static void EnableCrossSiteRequests(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute(
                origins: "*", 
                headers: "*", 
                methods: "*");
            config.EnableCors(cors);
        }
    }
    

    Values Controller

    The Get method receives the EnableCors attribute that we applied globally. The Another method overrides the global EnableCors.

    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable Get()
        {
            return new string[] { 
                "This is a CORS response.", 
                "It works from any origin." 
            };
        }
    
        // GET api/values/another
        [HttpGet]
        [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
        public IEnumerable Another()
        {
            return new string[] { 
                "This is a CORS response. ", 
                "It works only from two origins: ",
                "1. www.bigfont.ca ",
                "2. the same origin." 
            };
        }
    }
    

    Web.config

    You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.

    
    
    
    

    Demo

    var url = "https://cors-webapi.azurewebsites.net/api/values"
    
    $.get(url, function(data) {
      console.log("We expect this to succeed.");
      console.log(data);
    });
    
    var url = "https://cors-webapi.azurewebsites.net/api/values/another"
    
    $.get(url, function(data) {
      console.log(data);
    }).fail(function(xhr, status, text) {
      console.log("We expect this to fail.");
      console.log(status);
    });

提交回复
热议问题