C# 跨域 请求带cookie
原文: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的更多相关文章
- ajax跨域请求带cookie
调用网站:a.xxx.com jQuery(document).ready(function () { $.ajax({ type: "get", async: true, url ...
- Ajax跨域请求附带Cookie/Ajax跨域请求附带身份凭证
一.跨域请求中默认不带cookie等验证凭证 尤其对于post请求. 对于ajax请求,其中post,get都可以正常访问. withCredentials: false, // 允许携带cookie ...
- 【原】fetch跨域请求附带cookie(credentials)
HTTP访问控制 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS 解决跨域的方式有很多种,本文介绍" ...
- 关于 Angular 跨域请求携带 Cookie 的问题
在前端开发调试接口的时候都会遇到跨域请求的问题.传统的方式是使用 Nginx 反向代理解决跨域.比如所有接口都在 a.com 的域下,通过 Nginx 将所有请求代理到 a.com 的域下即可. 使用 ...
- 跨域请求携带cookie
function ajaxPostRequestCipherMachine(url, param) { var url = url; var dict = { 'ret' : false, 'er ...
- 跨域请求传递Cookie问题
问题描述 前后端完全分离的项目,前端使用Vue + axios,后端使用SpringMVC,容器为Tomcat. 使用CORS协议解决跨域访问数据限制的问题,但是发现客户端的Ajax请求不会自动带上服 ...
- asp.net web api 跨域,带cookie
官网上有一个介绍 http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api 但是只支 ...
- jquery中$.get()如何让跨域请求携带cookie?
在这个get请求前面加上这个就好了~~~~
- js跨域请求解决方案
什么是跨域? 跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的. 广义的跨域: 1.) 资源跳转: A链接.重定向.表单提交 2.) 资源嵌入: <link>.&l ...
随机推荐
- as3效率优化
1.改进算法无论对于那一种程序,好的算法总是非常重要的,而且能够极大地提高程序性能,所以任何性能的优化第一步就是从算法或者说程序逻辑的优化开始,检查自己的程序是否有多余的运算,是否在没有必要的时候做了 ...
- Redis Streams与Spark的完美结合
来源:Redislabs 作者:Roshan Kumar 翻译:Kevin (公众号:中间件小哥) 最近,我有幸在 Spark +AI 峰会上发表了题目为“Redis + Structured St ...
- kafka服务端实验记录
kafka单机实验: 环境准备: 1.下载kafka,zookeeper,并解压 wget http://mirror.bit.edu.cn/apache/kafka/2.3.0/kafka_2.11 ...
- ASP.NET Core 2.1 中的 HttpClientFactory (Part 3) 使用Handler实现传出请求中间件
原文:https://www.stevejgordon.co.uk/httpclientfactory-aspnetcore-outgoing-request-middleware-pipeline- ...
- C盘清理、C盘瘦身、省出30G
三招C盘瘦身30G,清理win10系统中虚占C盘空间的三大祸害 1.对C盘进行“磁盘清理” C盘右键->属性->磁盘清理->清理系统文件->勾选“windows更新清理”-&g ...
- Windows Server 2012 R2安装部署Office Web Apps Server
微软官方参考地址https://technet.microsoft.com/zh-cn/library/jj219455.aspx,建议参考官方说明. 注意:每一步进行完成后重启服务器!!! 一. ...
- ubuntu ufw 配置
ubuntu ufw 配置 Ubuntu 18.04 LTS 系统中已经默认附带了 UFW 工具,如果您的系统中没有安装,可以在「终端」中执行如下命令进行安装: 1 sudo apt install ...
- JavaScript仿百度图片浏览效果(转载)
转载来源:https://www.jb51.net/article/98030.htm 这是一个非常好的案例,然而jquery的时代正在徐徐关闭. 当你调整浏览器宽高,你会发现它不是自适应的.当你想把 ...
- nginx 是如何分配 worker 进程连接数的
客户端连接过来后,多个空闲的进程,会竞争这个连接,很容易看到,这种竞争会导致不公平,如果某个进程得到 accept 的机会比较多,它的空闲连接很快就用完了,如果不提前做一些控制,当 accept 到一 ...
- HTML&CSS基础-子元素的伪类选择器
HTML&CSS基础-子元素的伪类选择器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.html的源代码 <!DOCTYPE html> <html& ...