原文: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 文件中添加可跨域方法配置
-
-
-
using System.Web.Http.Cors;
-
namespace WebApplication1
-
-
public static class WebApiConfig
-
-
public static void Register(HttpConfiguration config)
-
-
var allowOrigin = ConfigurationManager.AppSettings["cors:allowOrigin"];
-
var allowHeaders = ConfigurationManager.AppSettings["cors:allowHeaders"];
-
var allowMethods = ConfigurationManager.AppSettings["cors:allowMethods"];
-
-
-
config.EnableCors(new EnableCorsAttribute(allowOrigin, allowHeaders, allowMethods));
-
-
-
config.MapHttpAttributeRoutes();
-
config.Routes.MapHttpRoute(
-
-
routeTemplate: "api/{controller}/{id}",
-
defaults: new { id = RouteParameter.Optional }
-
-
-
-
*****************************************************************************************************************
【注意:如果在 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>
指定站点允许跨域访问(基础类)
-
-
using System.Collections.Generic;
-
-
-
-
-
namespace WebApplication1.App_Start
-
-
public class AllowOriginAttribute
-
-
public static void onExcute(ControllerContext context, string[] AllowSites)
-
-
var origin = context.HttpContext.Request.Headers["Origin"];
-
-
-
context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
-
-
-
if (AllowSites != null && AllowSites.Any())
-
-
if (AllowSites.Contains(origin))
-
-
-
-
-
-
-
-
public class ActionAllowOriginAttribute : ActionFilterAttribute
-
-
public string[] AllowSites { get; set; }
-
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
-
-
AllowOriginAttribute.onExcute(filterContext, AllowSites);
-
base.OnActionExecuting(filterContext);
-
-
-
public class ControllerAllowOriginAttribute : AuthorizeAttribute
-
-
public string[] AllowSites { get; set; }
-
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
-
-
AllowOriginAttribute.onExcute(filterContext, AllowSites);
-
-
-
-
指定Controller允许跨域访问
-
[ControllerAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
-
public class CityController : Controller
-
指定Action允许跨域访问
-
-
[ActionAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
-
public ActionResult addCity(string userName, string password)
-
-
-
-
-
-
-
-
-
-
}, JsonRequestBehavior.AllowGet);
-
html页面
-
-
-
-
-
-
-
-
-
<meta name="viewport" content="width=device-width" />
-
-
<script src="~/Scripts/jquery-1.8.0.js"></script>
-
<script type="text/javascript">
-
-
-
-
-
-
url: "http://localhost:5640/City/addCity",
-
data: $('#form1').serialize(),
-
success: function (result) {
-
-
if (result.Code == 200) {
-
-
-
-
-
-
-
-
-
-
-
-
<form id="form1" onsubmit="return false" action="##" method="post">
-
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value="" /></p>
-
<p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value="" /></p>
-
<p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p>
-
-
-
XMLHttpRequest(原生)
-
-
-
var barcode = document.getElementById("Barcode").value;
-
var name = document.getElementById("Name").value;
-
-
console.log("1:" + barcode + ";2:" + name);
-
-
-
var xmlhttp = new XMLHttpRequest();
-
-
xmlhttp.open('post', 'http://localhost:52556/api/AssetOa?IsAddAsset=true', true);
-
-
-
-
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
-
-
-
xmlhttp.send('&Barcode=' + barcode + '&Name=' + name + '&AssetTypeId=1');
-
xmlhttp.onreadystatechange = function () {
-
-
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
-
console.log(xmlhttp.responseText);
-
-
-
【注意:仅能限制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 文件中添加可跨域方法配置
-
-
-
using System.Web.Http.Cors;
-
namespace WebApplication1
-
-
public static class WebApiConfig
-
-
public static void Register(HttpConfiguration config)
-
-
var allowOrigin = ConfigurationManager.AppSettings["cors:allowOrigin"];
-
var allowHeaders = ConfigurationManager.AppSettings["cors:allowHeaders"];
-
var allowMethods = ConfigurationManager.AppSettings["cors:allowMethods"];
-
-
-
config.EnableCors(new EnableCorsAttribute(allowOrigin, allowHeaders, allowMethods));
-
-
-
config.MapHttpAttributeRoutes();
-
config.Routes.MapHttpRoute(
-
-
routeTemplate: "api/{controller}/{id}",
-
defaults: new { id = RouteParameter.Optional }
-
-
-
-
*****************************************************************************************************************
【注意:如果在 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>
指定站点允许跨域访问(基础类)
-
-
using System.Collections.Generic;
-
-
-
-
-
namespace WebApplication1.App_Start
-
-
public class AllowOriginAttribute
-
-
public static void onExcute(ControllerContext context, string[] AllowSites)
-
-
var origin = context.HttpContext.Request.Headers["Origin"];
-
-
-
context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
-
-
-
if (AllowSites != null && AllowSites.Any())
-
-
if (AllowSites.Contains(origin))
-
-
-
-
-
-
-
-
public class ActionAllowOriginAttribute : ActionFilterAttribute
-
-
public string[] AllowSites { get; set; }
-
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
-
-
AllowOriginAttribute.onExcute(filterContext, AllowSites);
-
base.OnActionExecuting(filterContext);
-
-
-
public class ControllerAllowOriginAttribute : AuthorizeAttribute
-
-
public string[] AllowSites { get; set; }
-
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
-
-
AllowOriginAttribute.onExcute(filterContext, AllowSites);
-
-
-
-
指定Controller允许跨域访问
-
[ControllerAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
-
public class CityController : Controller
-
指定Action允许跨域访问
-
-
[ActionAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
-
public ActionResult addCity(string userName, string password)
-
-
-
-
-
-
-
-
-
-
}, JsonRequestBehavior.AllowGet);
-
html页面
-
-
-
-
-
-
-
-
-
<meta name="viewport" content="width=device-width" />
-
-
<script src="~/Scripts/jquery-1.8.0.js"></script>
-
<script type="text/javascript">
-
-
-
-
-
-
url: "http://localhost:5640/City/addCity",
-
data: $('#form1').serialize(),
-
success: function (result) {
-
-
if (result.Code == 200) {
-
-
-
-
-
-
-
-
-
-
-
-
<form id="form1" onsubmit="return false" action="##" method="post">
-
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value="" /></p>
-
<p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value="" /></p>
-
<p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p>
-
-
-
XMLHttpRequest(原生)
-
-
-
var barcode = document.getElementById("Barcode").value;
-
var name = document.getElementById("Name").value;
-
-
console.log("1:" + barcode + ";2:" + name);
-
-
-
var xmlhttp = new XMLHttpRequest();
-
-
xmlhttp.open('post', 'http://localhost:52556/api/AssetOa?IsAddAsset=true', true);
-
-
-
-
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
-
-
-
xmlhttp.send('&Barcode=' + barcode + '&Name=' + name + '&AssetTypeId=1');
-
xmlhttp.onreadystatechange = function () {
-
-
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
-
console.log(xmlhttp.responseText);
-
-
-