启用 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.Linq;
using System.Web.Http;
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("*", "*", "*"));
config.EnableCors(new EnableCorsAttribute(allowOrigin, allowHeaders, allowMethods));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
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;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.App_Start
{
public class AllowOriginAttribute
{
public static void onExcute(ControllerContext context, string[] AllowSites)
{
var origin = context.HttpContext.Request.Headers["Origin"];
Action action = () =>
{
context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
};
if (AllowSites != null && AllowSites.Any())
{
if (AllowSites.Contains(origin))
{
action();
}
}
}
}
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允许跨域访问
[HttpPost]
[ActionAllowOrigin(AllowSites = new string[] { "http://localhost:52559" })]
public ActionResult addCity(string userName, string password)
{
var a = userName;
var b = password;
return Json(new
{
Code = 200,
msg = "123",
data = ""
}, JsonRequestBehavior.AllowGet);
}
html页面
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexTest</title>
<script src="~/Scripts/jquery-1.8.0.js"></script>
<script type="text/javascript">
function login() {
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "http://localhost:5640/City/addCity",//url
data: $('#form1').serialize(),
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.Code == 200) {
alert("SUCCESS");
}
},
error: function () {
alert("异常!");
}
});
}
</script>
</head>
<body>
<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>
</form>
</body>
</html>
XMLHttpRequest(原生)
function loginNew() {
var barcode = document.getElementById("Barcode").value;
var name = document.getElementById("Name").value;
console.log("1:" + barcode + ";2:" + name);
//创建异步对象
var xmlhttp = new XMLHttpRequest();
//设置请求的类型及url
xmlhttp.open('post', 'http://localhost:52556/api/AssetOa?IsAddAsset=true', true);
//post请求一定要添加请求头才行不然会报错
//xmlhttp.setRequestHeader("Content-type", "application/json");
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);
}
};
}
D:\MyFile\测试项目\Solution1\WebApplication1