.net 跨域 问题解决

参考地址:http://www.cnblogs.com/moretry/p/4154479.html

在项目上面使用 Nuget 搜索 microsoft.aspnet.webapi.cors 直接下载安装即可

然后在 App_Start 文件夹下面的 WebApiConfig.cs 文件夹配置跨域,这里是配置全局跨域

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //跨域配置
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            // Web API 路由
            config.MapHttpAttributeRoutes();

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

局部配置跨域 

可以在某个方法或者ApiController上这样配置:[EnableCors(origins: "*", headers: "*", methods: "*")],可以使用具体的参数,多个参数以逗号分隔。origins 域名要带上http的顶级域名。

需要添加 using System.Web.Http.Cors;

.net core 配置跨域

 在 Startup.cs 文件 配置如下

 public void ConfigureServices(IServiceCollection services)
        {
            //跨域操作
            services.AddCors(o => o.AddPolicy("AllowSpecificOrigin", builder =>
                 builder.AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader()));
            ;
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            //跨域操作
            app.UseCors("AllowSpecificOrigin");
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

 

 

posted @ 2017-11-08 16:30  ice.ko  阅读(539)  评论(0编辑  收藏  举报