zoukankan      html  css  js  c++  java
  • .net 跨域问题 CORS

    原文:https://blog.csdn.net/KingCruel/article/details/80229589

    启用 ASP.NET Core 中的跨域请求 (CORS)  
    ASP.NET Core 启用跨域请求 (CORS)

    【注意:仅能限制ajax json请求,不能限制ajax jsonp请求,本地修改了host文件,配置了不同域名,已经反复测试证实。】
    在 ASP.NET Web API 项目中使用 Cross Origin Resource Sharing(CORS),解决一些跨域域请求问题,可以直接用 Ajax 调用 Web API 接口

    1、管理 NuGet 添加引用
         Microsoft.AspNet.Cors
         注:在OWIN 中需要引用的是 Microsoft.AspNet.WebApi.Cors

    2、在 WebApiConfig 文件中添加可跨域方法配置

    1.  
      using System.Linq;
    2.  
      using System.Web.Http;
    3.  
      using System.Web.Http.Cors;
    4.  
      namespace WebApplication1
    5.  
      {
    6.  
      public static class WebApiConfig
    7.  
      {
    8.  
      public static void Register(HttpConfiguration config)
    9.  
      {
    10.  
      var allowOrigin = ConfigurationManager.AppSettings["cors:allowOrigin"];
    11.  
      var allowHeaders = ConfigurationManager.AppSettings["cors:allowHeaders"];
    12.  
      var allowMethods = ConfigurationManager.AppSettings["cors:allowMethods"];
    13.  
       
    14.  
      //config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
    15.  
      config.EnableCors(new EnableCorsAttribute(allowOrigin, allowHeaders, allowMethods));
    16.  
       
    17.  
       
    18.  
      config.MapHttpAttributeRoutes();
    19.  
      config.Routes.MapHttpRoute(
    20.  
      name: "DefaultApi",
    21.  
      routeTemplate: "api/{controller}/{id}",
    22.  
      defaults: new { id = RouteParameter.Optional }
    23.  
      );
    24.  
      }
    25.  
      }
    26.  
      }

    *****************************************************************************************************************
    【注意:如果在 web api 项目中配置了如上信息,可以跨域请求到接口,但是不能返回数据,提示错误信息,考虑把web api 项目中的 web.config 文件中的 httpProtocol 节点删除掉】
    *****************************************************************************************************************

    ********
    ********
    ********
    ********

    web.config文件中的 system.webServer 节点下增加如下配置:

    <!--允许跨域 参考 开始-->
    <appSettings>  
      <add key="cors:allowMethods" value="*" />
      <add key="cors:allowOrigin" value="*" />
      <add key="cors:allowHeaders" value="*" />
    </appSettings>
    <!--允许跨域 参考 结束-->
    <system.web>
      <authentication mode="None" />
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
    <system.webServer>
      <!--允许跨域 开始-->
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        </customHeaders>
      </httpProtocol>
      <!--允许跨域 结束-->
    </system.webServer>

    指定站点允许跨域访问(基础类)

    1.  
      using System;
    2.  
      using System.Collections.Generic;
    3.  
      using System.Linq;
    4.  
      using System.Web;
    5.  
      using System.Web.Mvc;
    6.  
       
    7.  
      namespace WebApplication1.App_Start
    8.  
      {
    9.  
      public class AllowOriginAttribute
    10.  
      {
    11.  
      public static void onExcute(ControllerContext context, string[] AllowSites)
    12.  
      {
    13.  
      var origin = context.HttpContext.Request.Headers["Origin"];
    14.  
      Action action = () =>
    15.  
      {
    16.  
      context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
    17.  
       
    18.  
      };
    19.  
      if (AllowSites != null && AllowSites.Any())
    20.  
      {
    21.  
      if (AllowSites.Contains(origin))
    22.  
      {
    23.  
      action();
    24.  
      }
    25.  
      }
    26.  
      }
    27.  
      }
    28.  
       
    29.  
      public class ActionAllowOriginAttribute : ActionFilterAttribute
    30.  
      {
    31.  
      public string[] AllowSites { get; set; }
    32.  
      public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
    33.  
      {
    34.  
      AllowOriginAttribute.onExcute(filterContext, AllowSites);
    35.  
      base.OnActionExecuting(filterContext);
    36.  
      }
    37.  
      }
    38.  
      public class ControllerAllowOriginAttribute : AuthorizeAttribute
    39.  
      {
    40.  
      public string[] AllowSites { get; set; }
    41.  
      public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    42.  
      {
    43.  
      AllowOriginAttribute.onExcute(filterContext, AllowSites);
    44.  
      }
    45.  
       
    46.  
      }
    47.  
      }

     

     

     

    指定Controller允许跨域访问

     

    1.  
      [ControllerAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
    2.  
      public class CityController : Controller
    3.  
      {}

     

     

     

    指定Action允许跨域访问

     

    1.  
      [HttpPost]
    2.  
      [ActionAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
    3.  
      public ActionResult addCity(string userName, string password)
    4.  
      {
    5.  
      var a = userName;
    6.  
      var b = password;
    7.  
       
    8.  
      return Json(new
    9.  
      {
    10.  
      Code = 200,
    11.  
      msg = "123",
    12.  
      data = ""
    13.  
      }, JsonRequestBehavior.AllowGet);
    14.  
      }


    html页面

     

     

     

     

    1.  
      @{
    2.  
      Layout = null;
    3.  
      }
    4.  
       
    5.  
      <!DOCTYPE html>
    6.  
       
    7.  
      <html>
    8.  
      <head>
    9.  
      <meta name="viewport" content="width=device-width" />
    10.  
      <title>IndexTest</title>
    11.  
      <script src="~/Scripts/jquery-1.8.0.js"></script>
    12.  
      <script type="text/javascript">
    13.  
      function login() {
    14.  
      $.ajax({
    15.  
      //几个参数需要注意一下
    16.  
      type: "POST",//方法类型
    17.  
      dataType: "json",//预期服务器返回的数据类型
    18.  
      url: "http://localhost:5640/City/addCity",//url
    19.  
      data: $('#form1').serialize(),
    20.  
      success: function (result) {
    21.  
      console.log(result);//打印服务端返回的数据(调试用)
    22.  
      if (result.Code == 200) {
    23.  
      alert("SUCCESS");
    24.  
      }
    25.  
      },
    26.  
      error: function () {
    27.  
      alert("异常!");
    28.  
      }
    29.  
      });
    30.  
      }
    31.  
      </script>
    32.  
      </head>
    33.  
      <body>
    34.  
      <form id="form1" onsubmit="return false" action="##" method="post">
    35.  
      <p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value="" /></p>
    36.  
      <p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value="" /></p>
    37.  
      <p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p>
    38.  
      </form>
    39.  
      </body>
    40.  
      </html>

     

    XMLHttpRequest(原生)

     

    1.  
      function loginNew() {
    2.  
       
    3.  
      var barcode = document.getElementById("Barcode").value;
    4.  
      var name = document.getElementById("Name").value;
    5.  
       
    6.  
      console.log("1:" + barcode + ";2:" + name);
    7.  
       
    8.  
      //创建异步对象
    9.  
      var xmlhttp = new XMLHttpRequest();
    10.  
      //设置请求的类型及url
    11.  
      xmlhttp.open('post', 'http://localhost:52556/api/AssetOa?IsAddAsset=true', true);
    12.  
       
    13.  
      //post请求一定要添加请求头才行不然会报错
    14.  
      //xmlhttp.setRequestHeader("Content-type", "application/json");
    15.  
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    16.  
       
    17.  
      //发送请求
    18.  
      xmlhttp.send('&Barcode=' + barcode + '&Name=' + name + '&AssetTypeId=1');
    19.  
      xmlhttp.onreadystatechange = function () {
    20.  
      // 这步为判断服务器是否正确响应
    21.  
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    22.  
      console.log(xmlhttp.responseText);
    23.  
      }
    24.  
      };
    25.  
      }

    【注意:仅能限制ajax json请求,不能限制ajax jsonp请求,本地修改了host文件,配置了不同域名,已经反复测试证实。】
    在 ASP.NET Web API 项目中使用 Cross Origin Resource Sharing(CORS),解决一些跨域域请求问题,可以直接用 Ajax 调用 Web API 接口

    1、管理 NuGet 添加引用
         Microsoft.AspNet.Cors
         注:在OWIN 中需要引用的是 Microsoft.AspNet.WebApi.Cors

    2、在 WebApiConfig 文件中添加可跨域方法配置

    1.  
      using System.Linq;
    2.  
      using System.Web.Http;
    3.  
      using System.Web.Http.Cors;
    4.  
      namespace WebApplication1
    5.  
      {
    6.  
      public static class WebApiConfig
    7.  
      {
    8.  
      public static void Register(HttpConfiguration config)
    9.  
      {
    10.  
      var allowOrigin = ConfigurationManager.AppSettings["cors:allowOrigin"];
    11.  
      var allowHeaders = ConfigurationManager.AppSettings["cors:allowHeaders"];
    12.  
      var allowMethods = ConfigurationManager.AppSettings["cors:allowMethods"];
    13.  
       
    14.  
      //config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
    15.  
      config.EnableCors(new EnableCorsAttribute(allowOrigin, allowHeaders, allowMethods));
    16.  
       
    17.  
       
    18.  
      config.MapHttpAttributeRoutes();
    19.  
      config.Routes.MapHttpRoute(
    20.  
      name: "DefaultApi",
    21.  
      routeTemplate: "api/{controller}/{id}",
    22.  
      defaults: new { id = RouteParameter.Optional }
    23.  
      );
    24.  
      }
    25.  
      }
    26.  
      }

    *****************************************************************************************************************
    【注意:如果在 web api 项目中配置了如上信息,可以跨域请求到接口,但是不能返回数据,提示错误信息,考虑把web api 项目中的 web.config 文件中的 httpProtocol 节点删除掉】
    *****************************************************************************************************************

    ********
    ********
    ********
    ********

    web.config文件中的 system.webServer 节点下增加如下配置:

    <!--允许跨域 参考 开始-->
    <appSettings>  
      <add key="cors:allowMethods" value="*" />
      <add key="cors:allowOrigin" value="*" />
      <add key="cors:allowHeaders" value="*" />
    </appSettings>
    <!--允许跨域 参考 结束-->
    <system.web>
      <authentication mode="None" />
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
    <system.webServer>
      <!--允许跨域 开始-->
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        </customHeaders>
      </httpProtocol>
      <!--允许跨域 结束-->
    </system.webServer>

    指定站点允许跨域访问(基础类)

    1.  
      using System;
    2.  
      using System.Collections.Generic;
    3.  
      using System.Linq;
    4.  
      using System.Web;
    5.  
      using System.Web.Mvc;
    6.  
       
    7.  
      namespace WebApplication1.App_Start
    8.  
      {
    9.  
      public class AllowOriginAttribute
    10.  
      {
    11.  
      public static void onExcute(ControllerContext context, string[] AllowSites)
    12.  
      {
    13.  
      var origin = context.HttpContext.Request.Headers["Origin"];
    14.  
      Action action = () =>
    15.  
      {
    16.  
      context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
    17.  
       
    18.  
      };
    19.  
      if (AllowSites != null && AllowSites.Any())
    20.  
      {
    21.  
      if (AllowSites.Contains(origin))
    22.  
      {
    23.  
      action();
    24.  
      }
    25.  
      }
    26.  
      }
    27.  
      }
    28.  
       
    29.  
      public class ActionAllowOriginAttribute : ActionFilterAttribute
    30.  
      {
    31.  
      public string[] AllowSites { get; set; }
    32.  
      public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
    33.  
      {
    34.  
      AllowOriginAttribute.onExcute(filterContext, AllowSites);
    35.  
      base.OnActionExecuting(filterContext);
    36.  
      }
    37.  
      }
    38.  
      public class ControllerAllowOriginAttribute : AuthorizeAttribute
    39.  
      {
    40.  
      public string[] AllowSites { get; set; }
    41.  
      public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    42.  
      {
    43.  
      AllowOriginAttribute.onExcute(filterContext, AllowSites);
    44.  
      }
    45.  
       
    46.  
      }
    47.  
      }

     

     

     

    指定Controller允许跨域访问

     

    1.  
      [ControllerAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
    2.  
      public class CityController : Controller
    3.  
      {}

     

     

     

    指定Action允许跨域访问

     

    1.  
      [HttpPost]
    2.  
      [ActionAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
    3.  
      public ActionResult addCity(string userName, string password)
    4.  
      {
    5.  
      var a = userName;
    6.  
      var b = password;
    7.  
       
    8.  
      return Json(new
    9.  
      {
    10.  
      Code = 200,
    11.  
      msg = "123",
    12.  
      data = ""
    13.  
      }, JsonRequestBehavior.AllowGet);
    14.  
      }


    html页面

     

     

     

     

    1.  
      @{
    2.  
      Layout = null;
    3.  
      }
    4.  
       
    5.  
      <!DOCTYPE html>
    6.  
       
    7.  
      <html>
    8.  
      <head>
    9.  
      <meta name="viewport" content="width=device-width" />
    10.  
      <title>IndexTest</title>
    11.  
      <script src="~/Scripts/jquery-1.8.0.js"></script>
    12.  
      <script type="text/javascript">
    13.  
      function login() {
    14.  
      $.ajax({
    15.  
      //几个参数需要注意一下
    16.  
      type: "POST",//方法类型
    17.  
      dataType: "json",//预期服务器返回的数据类型
    18.  
      url: "http://localhost:5640/City/addCity",//url
    19.  
      data: $('#form1').serialize(),
    20.  
      success: function (result) {
    21.  
      console.log(result);//打印服务端返回的数据(调试用)
    22.  
      if (result.Code == 200) {
    23.  
      alert("SUCCESS");
    24.  
      }
    25.  
      },
    26.  
      error: function () {
    27.  
      alert("异常!");
    28.  
      }
    29.  
      });
    30.  
      }
    31.  
      </script>
    32.  
      </head>
    33.  
      <body>
    34.  
      <form id="form1" onsubmit="return false" action="##" method="post">
    35.  
      <p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value="" /></p>
    36.  
      <p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value="" /></p>
    37.  
      <p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p>
    38.  
      </form>
    39.  
      </body>
    40.  
      </html>

     

    XMLHttpRequest(原生)

     

    1.  
      function loginNew() {
    2.  
       
    3.  
      var barcode = document.getElementById("Barcode").value;
    4.  
      var name = document.getElementById("Name").value;
    5.  
       
    6.  
      console.log("1:" + barcode + ";2:" + name);
    7.  
       
    8.  
      //创建异步对象
    9.  
      var xmlhttp = new XMLHttpRequest();
    10.  
      //设置请求的类型及url
    11.  
      xmlhttp.open('post', 'http://localhost:52556/api/AssetOa?IsAddAsset=true', true);
    12.  
       
    13.  
      //post请求一定要添加请求头才行不然会报错
    14.  
      //xmlhttp.setRequestHeader("Content-type", "application/json");
    15.  
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    16.  
       
    17.  
      //发送请求
    18.  
      xmlhttp.send('&Barcode=' + barcode + '&Name=' + name + '&AssetTypeId=1');
    19.  
      xmlhttp.onreadystatechange = function () {
    20.  
      // 这步为判断服务器是否正确响应
    21.  
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    22.  
      console.log(xmlhttp.responseText);
    23.  
      }
    24.  
      };
    25.  
      }

     

  • 相关阅读:
    理解闭包
    .net 应用程序执行过程
    Lambda 表达式
    栈的应用
    C# string
    自包含 与 自描述
    C# 值类型 与 引用类型
    C# 装箱 与 拆箱
    sql server分页的两种方法比较
    九月天开博日志
  • 原文地址:https://www.cnblogs.com/zhang1f/p/14393092.html
Copyright © 2011-2022 走看看