原文: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. (一)Django项目的目录结构

    1.将app放在apps文件夹中,将改文件夹设置为 source root,便于引用.两个app不可以互相引用,可以利用第三个app实现一些操作. 2.将一些多媒体文件放在media中的相应app名称 ...

  2. Expanded, SingleChildScrollView, CustomScrollView, container, height, width

    SingleChildScrollView, CustomScrollView, container, init: double.inifinity. then use Expanded to con ...

  3. Cookie 和 Session 总结

    Cookie 和 Session 区别 cookie数据存放在客户的浏览器上,session数据放在服务器上 cookie不是很安全,别人可以分析存放在本地的cookie并进行cookie欺骗,考虑* ...

  4. HDFS-SecondaryNameNode(SNN)角色介绍

    它出现在Hadoop1.x版本中,又称辅助NameNode,在Hadoop2.x以后的版本中此角色消失.如果充当datanode节点的一台机器宕机或者损害,其数据不会丢失,因为备份数据还存在于其他的d ...

  5. IDEA中导入Maven模块

    IDEA中导入Maven模块方式有二种: 1)批量添加,不可添加文件夹 2)单个添加,可添加任意文件

  6. django获取数据queryset中的filter选项

    2.条件选取querySet的时候,filter表示=,exclude表示!=. querySet.distinct() 去重复__exact 精确等于 like 'aaa' __iexact 精确等 ...

  7. Debian9.5系统安装

    1.镜像下载地址 http://cdimage.debian.org/cdimage/archive/ 2.开始安装 如果有配置网络地址,可以手动配置或者跳过等系统安装好后配置.  至此debian9 ...

  8. ssh本机失败(ssh: connect to host localhost port 22: Connection refused)

    ssh本机失败(ssh: connect to host localhost port 22: Connection refused) 一. 问题描述 之前一直在服务上使用宝塔面板, 今天突发奇想, ...

  9. (Linux基础学习)第一章:科普和Linux系统安装

    第一章:科普和Linux系统安装 第1节:操作系统介绍OS:Operating System,通用目的的软件程序硬件驱动进程管理内存管理网络管理安全管理文件管理OS分类:服务器OS:RHEL,Cent ...

  10. websocket实现心跳连接

    在使用websocket的时候,遇到了一个websocket在连接一段时间就异常断开连接了.第一想法就是重新去连接websocket(websock.onopen),后来发现这种方式是错误的,查阅文档 ...