zoukankan      html  css  js  c++  java
  • 在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。

  • 相关阅读:
    管理信息系统 第三部分 作业
    密码保护
    实现搜索功能
    完成个人中心—导航标签
    个人中心标签页导航
    评论列表显示及排序,个人中心显示
    完成评论功能
    管理信息系统 课程设计
    期末作品检查
    管理信息系统 第三部分 作业
  • 原文地址:https://www.cnblogs.com/darrenji/p/4913139.html
Copyright © 2011-2022 走看看