原文:https://blog.csdn.net/z69183787/article/details/78954325
背景:
别个的项目,要开发App接口,要求用前端AJAX的方式访问接口数据。
后台项目用的asp.net mvc,但是所有的方法都是写在controller层里面的,
App接口要求的功能大部分都是controller层里面的方法,
肯定不可能再重新写一遍接口咯,时间也来不及,并且方法也会重复,不利于维护。
主要做了两点:
1、让后端支持跨域
2、跨域时附带把cookie传过去
这里有一个坑,特别注意哈!!!:服务器端 Access-Control-Allow-Credentials = true时,参数Access-Control-Allow-Origin 的值不能为 '*' 。
跨域的代码:
后端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace CLBIM.Filter
{
/// <summary>
/// 运行跨域
/// </summary>
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
private string[] _domains; public AllowCrossSiteJsonAttribute()
{
_domains = new string[] { };
}
public AllowCrossSiteJsonAttribute(string domain)
{
_domains = new string[] { domain };
}
public AllowCrossSiteJsonAttribute(string[] domains)
{
_domains = domains;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//var context = filterContext.RequestContext.HttpContext;
//var host = context.Request.UrlReferrer?.Host;
//if (host != null && _domains.Contains(host))
//{
// filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
//} //服务器端 Access-Control-Allow-Credentials = true时,参数Access-Control-Allow-Origin 的值不能为 '*' 。
var Origin = filterContext.RequestContext.HttpContext.Request.Headers["Origin"];
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", Origin);
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
base.OnActionExecuting(filterContext);
}
}
}
前端:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<style type="text/css">
input {
width: 200px;
margin: 5px;
height: 30px;
}
</style>
<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body> <div id="div1"></div> <script type="text/javascript"> var url = 'http://192.168.2.73:9012';//远程服务地址
url = 'http://183.66.231.18:8050'; //带cookie的方式
//查看返回的数据:F12 -> Network -> XHR -> 点开一个具体的请求 -> Preview //登录
function fn1() {
var model = {
UserName: "admin",
Password: "123456",
};
$.ajax({
type: "POST",
url: url + "/Login/VerifyLogin",
data: model,
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (response) {
console.log(response);//返回的内容
}
});
} //退出登录
function fn2() {
$.ajax({
type: "POST",
url: url + "/Login/LogOut",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (response) {
console.log(response);
}
});
} //获取菜单
function fn3() {
$.ajax({
type: "POST",
url: url + "/SystemManage/Menu/GetAllMenu",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (response) {
console.log(response);
}
});
} //生成按钮 var fn_names = [];
fn_names.push("带cookie-登录");
fn_names.push("带cookie-退出登录");
fn_names.push("带cookie-获取菜单"); var CreateHtml = function () {
var strHtml = '';
for (var i = 0; i < fn_names.length; i++) {
var num = i + 1;
var name = fn_names[i];
strHtml += '<input type="button" value="fn' + num + ' ' + name + '" onclick="fn' + num + '()" />';
}
$("#div1").html(strHtml);
}(); </script> </body>
</html>
注意一下ajax的配置参数:
function fn1() {
var model = {
UserName: "admin",
Password: "123456",
};
$.ajax({
type: "POST",
url: url + "/Login/VerifyLogin",
data: model,
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (response) {
console.log(response);//返回的内容
}
});
}
后端主要代码:
var Origin = filterContext.RequestContext.HttpContext.Request.Headers["Origin"];
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", Origin);
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");