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

后端 未结 11 558
庸人自扰
庸人自扰 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:44

    You just need to change some files. This works for me.

    Global.ascx

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

    WebApiConfig.cs

    All the requests has to call this code.

    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);
        } }
    

    Some Controller

    Nothing to change.

    Web.config

    You need to add handlers in your web.config

     
      
        
          
          
          
          
           
       
    
    

提交回复
热议问题