• 在ASP.NET Web API中实现CORS(跨域资源共享)


    默认情况下,是不允许网页从不同的域访问服务器资源的,访问遵循"同源"策略的原则。

    会遇到如下的报错:


    XMLHttpRequest cannot load http://localhost:49705//api/products. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49729' is therefore not allowed access.

    初始或源域名是:http://localhost:49729/
    请求产品的域名是:http://localhost:49705//api/products

    由于端口号不一致,所以,在"同源"策略下,服务器资源是被禁止访问的,会报错。


    ASP.NET Web API为我们提供了实现CORS(跨域资源共享)的解决方案。


    首先通过NuGet安装:microsoft asp.ent web api 202 cross-origin support


    在WebConfig类中配置如下:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
           ...
    
            // Web API 路由
            config.MapHttpAttributeRoutes();
    
            //全局允许CROS
            config.EnableCors();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
    
        }
    }

    在ApiController上设置CROS属性。

    [EnableCorsAttribute("http://localhost:49729","*","*")]
    public class ProductsController : ApiController
    {
    ...
    }

    以上就实现了在ASP.NET Web API中的CROS。

  • 相关阅读:
    【iPhone开发】说说Xcode4中xib绑定的原理转
    转 IOS下的图片
    免证书调试Iphone程序(转)
    牛B的Python模块(转)
    6 个手机开发方面很有用的应用
    留个脚印!
    Android初学者入门PDF版
    IOS下的MVC
    android2.2源码编译-Ubuntu10.04 (X86) + android2.2 + JDK1.6
    10 款 Windows 下最佳的免费 PHP 编辑器
  • 原文地址:https://www.cnblogs.com/darrenji/p/4913139.html
Copyright © 2020-2023  润新知