zoukankan      html  css  js  c++  java
  • webapi使用System.Web.Http.Cors配置跨域访问的两种方式

    System.Web.Http.Cors配置跨域访问的两种方式

     方式一:

     App_Start.WebApiConfig.cs的Register中配置如下代码,

     这种方式将在所有的webapi Controller里面起作用。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    using System.Web.Http.Cors;
    
    namespace YDTG.Service
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API 配置和服务
    
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                //这是重点,从配置文件的appsettings节点中读取跨域的地址
                var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["origins"], "*", "*");
                config.EnableCors(cors);
            }
        }
    }

    配置文件如下,注意一定要加上http

    <add key="origins" value="http://localhost:9012,http://192.168.1.108:9012" />

    方式二:

    每个webapiController类中设置,即每个控制器个性化配置,如下代码。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http.Cors;
    using System.Web.Mvc;
    
    namespace Service.Controllers
    {
        [EnableCors("http://localhost:9012,http://192.168.1.108:9012", "*", "*")]
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewBag.Title = "Home Page";
    
                return View();
            }
        }
    }

    注意事项

    1. EnableCors共三个参数分别为origins、headers和methods。origins配置允许访问的域名,多个域名以逗号分隔即可,域名一定要完整,如果是ip地址前面要加上“http”,只使用IP的话一定会失效的。参数headers配置所支持的资源。参数methods配置支持的方法,get、post、put等。如果允许任意域名、任意资源、任意方法访问自己的webapi,则三个参数全部使用星号”*”即可。
    2. “EnableCors(“http://localhost:9012,http://192.168.1.108:9012“, ““, ““)”中的配置如果出现错误的话不会报错,而是直接禁止未出现在配置表中的资源访问。
    3. 如果使用第一种方式那么可以从配置文件中读取网站列表,如果使用第二种方式,所有的参数只能使用常量。

    本文引自:https://blog.csdn.net/chaoyangzhixue/article/details/52251322

  • 相关阅读:
    Java中的四种内部类
    用输入/输出写一个程序,让用户输入一些姓名和电话号码
    分批读取大数据问题
    Linux产生序列数字
    两个有序链表的合并
    int和Integer的区别
    wait()和sleep()的区别
    Unix和Windows文件格式转化
    截取字符串的代码实现
    查看系统信息
  • 原文地址:https://www.cnblogs.com/ggll611928/p/14439209.html
Copyright © 2011-2022 走看看