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 ...
随机推荐
- springboot项目 配置https
感谢 https://www.jianshu.com/p/1b7b9e0803c6 帮我解决了问题 生成自签名证书 keytool -genkey -storetype PKCS12 -keysiz ...
- PHP写入文件
file_put_contents('log.txt',PHP_EOL.'zhangsan'.$time.'查看了数据', FILE_APPEND);
- activiti串行会签的使用
1.串行任务的配置 2.当任务走到串行会签节点时,会从你之前保存的流程变量中找集合(我这里设置的assigneeList),串行会签会根据这个集合设置一系列该节点的流程变量 3.结束条件的设置,若满足 ...
- 支付宝支付回调方法RSA2验签失败处理方法
支付宝支付签名方式RSA2生成支付时使用的是支付宝公钥和应用私钥, 而不是应用公钥,支付宝公钥的生成是根据上传应用公钥而变动的, 所以在做回调的时候参数ALIPAY_PUBLIC_KEY也需要传支付宝 ...
- emacs手动安装、解决不能使用中文输入法
emacs的安装 emacs的下载,解压 wget http://mirrors.ustc.edu.cn/gnu/emacs/emacs-25.3.tar.gz tar -zxf emacs-25.3 ...
- JavaScript的变量和常量
1.什么是常量? 常量表示一些固定不变的数据 现实生活中人的性别其实就可以看做是常量, 生下来是男孩一辈子都是男孩, 生下来是女孩一辈子都是女孩 2.JavaScript中常量的分类 2.1整型常量 ...
- day27-python之迭代器协议
1.item系列方法 # class Foo: # def __getitem__(self, item): # print('getitem',item) # return self.__dict_ ...
- SpringMVC框架笔记01_SpringMVC的使用案例和架构组件_SpringMVC和Mybatis整合_接收参数
目录 第1章:SpringMVC简介 1.1 什么是SpringMVC 1.2 SpringMVC的处理流程 第2章:SpringMVC入门程序 2.1 场景描述 2.2 步骤分析 2.3 步骤一:创 ...
- ubuntu下关于profile和bashrc中环境变量的理解(转)
ubuntu下关于profile和bashrc中环境变量的理解(转) (0) 写在前面 有些名词可能需要解释一下.(也可以先不看这一节,在后面看到有疑惑再上来看相关解释) $PS1和交互式运行(r ...
- TP5框架模块绑定二级域名
application\config.php 修改 url_domain_deploy 为 true 'url_domain_deploy' => true application\route. ...