原文: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");

C# 跨域 请求带cookie的更多相关文章

  1. ajax跨域请求带cookie

    调用网站:a.xxx.com jQuery(document).ready(function () { $.ajax({ type: "get", async: true, url ...

  2. Ajax跨域请求附带Cookie/Ajax跨域请求附带身份凭证

    一.跨域请求中默认不带cookie等验证凭证 尤其对于post请求. 对于ajax请求,其中post,get都可以正常访问. withCredentials: false, // 允许携带cookie ...

  3. 【原】fetch跨域请求附带cookie(credentials)

    HTTP访问控制 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS 解决跨域的方式有很多种,本文介绍" ...

  4. 关于 Angular 跨域请求携带 Cookie 的问题

    在前端开发调试接口的时候都会遇到跨域请求的问题.传统的方式是使用 Nginx 反向代理解决跨域.比如所有接口都在 a.com 的域下,通过 Nginx 将所有请求代理到 a.com 的域下即可. 使用 ...

  5. 跨域请求携带cookie

      function ajaxPostRequestCipherMachine(url, param) { var url = url; var dict = { 'ret' : false, 'er ...

  6. 跨域请求传递Cookie问题

    问题描述 前后端完全分离的项目,前端使用Vue + axios,后端使用SpringMVC,容器为Tomcat. 使用CORS协议解决跨域访问数据限制的问题,但是发现客户端的Ajax请求不会自动带上服 ...

  7. asp.net web api 跨域,带cookie

    官网上有一个介绍 http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api 但是只支 ...

  8. jquery中$.get()如何让跨域请求携带cookie?

    在这个get请求前面加上这个就好了~~~~

  9. js跨域请求解决方案

    什么是跨域? 跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的. 广义的跨域: 1.) 资源跳转: A链接.重定向.表单提交 2.) 资源嵌入: <link>.&l ...

随机推荐

  1. TypeScript之泛型

    什么是泛型,有什么用? 泛型字面意思就是广泛的类型,怎么样才算广泛呢?当然是能变的最广泛嘛, 所谓泛型就是类型的变量写法,让你的变量的类型是动态可变的,应用场景如官方文档描述的例子: 一个函数,输入什 ...

  2. Unity的学习笔记(摇杆制作)

    最近看到了一个很新颖的摇杆,就是按下后,会出现在按下的位置,并且拖着走的时候,到一定距离整个摇杆也会跟着走,于是自己测试做了一下这种摇杆 首先,先说一下我的摇杆预设体结构 代码挂在哪里都无所谓,关键是 ...

  3. console.log()、console.info()、console.debug()的区别

    onsole.log().console.info().console.debug()的作用都是在浏览器控制台打印信息的. 使用最多的是console.log().console.info()和con ...

  4. vue 自定义image组件

    介绍 1:当图片加载失败时,给出错误提示. 2:当图片加载中时,给出加载提示. 3:图片处理模式:等比缩放/裁剪/填充/... 1.图片加载状态处理 通过给图片绑定load事件与error事件处理函数 ...

  5. python day4 元组/字典/集合类知识点补充

    目录 python day4 元组/字典/集合类知识点补充 1. 元组tuple知识点补充 2. 字典dict的知识点补充 3. 基本数据类型set 4. 三元运算,又叫三目运算 5. 深复制浅复制 ...

  6. JSP中Get提交方式的中文乱码解决

    最近对JSP&Servlert的原理很感兴趣,所以今天花时间看了一下:无奈在一个编码问题上困扰很久 这是我的解决思路: (1)检查网页(html/jsp)页面的编码: (2)检查服务器端的处理 ...

  7. out string

    示例 当希望方法返回多个值时,声明 out 方法很有用.使用 out 参数的方法仍然可以将变量用作返回类型(请参见 return),但它还可以将一个或多个对象作为 out 参数返回给调用方法.此示例使 ...

  8. 批处理引擎MapReduce编程模型

    批处理引擎MapReduce编程模型 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. MapReduce是一个经典的分布式批处理计算引擎,被广泛应用于搜索引擎索引构建,大规模数据处理 ...

  9. ntohs的一个简单实现(将网络流中用两个字节16进制表示的资源数(如DNS)和长度转换为整形)

    我们知道在由于大端机和小端机导致网络字节序和主机序有可能是有差异的,我们可以使用系统的ntohs,ntohl,htons和htonl这些处理函数进行转换,下面是我写的一个关于ntohs在处理小端机字节 ...

  10. python3 tkinter模块

    一.tkinter 1.tkinter--tool kit interface工具包接口,用于GUI(Graphical User Interface)用户图形界面, 2.python3.x把Tkin ...