|
ASP.NET Core 启用跨域请求 (CORS)
web.config文件中的 system.webServer 节点下增加如下配置:
<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" οnsubmit="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="登录" οnclick="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 |