原文: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. 基于 Docker 和 GitLab 的前端自动化部署实践笔记

    基于 Docker 和 GitLab 的前端自动化部署 实践笔记 随着接触的项目越来越多,在部署测试流程上重复耗时工作也越来越多,所以对前端工作的CI/CD实现愈发迫在眉睫. 前端开发由于三大框架的崛 ...

  2. 【LEETCODE】57、数组分类,适中级别,题目:969、442、695

    package y2019.Algorithm.array.medium; import java.util.ArrayList; import java.util.List; /** * @Proj ...

  3. 【LEETCODE】38、167题,Two Sum II - Input array is sorted

    package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...

  4. 解决跟Docker私有仓库登陆,推送,拉取镜像出现的报错

    出现问题:Error response from daemon: Get https://192.168.186.120/v1/users/: dial tcp 192.168.186.120:443 ...

  5. GOF 的23种JAVA常用设计模式总结 03 面向对象七大设计原则

    在软件开发中,为了提高软件系统的可维护性和可复用性,增加软件的可扩展性和灵活性,程序员要尽量根据 7 条原则来开发程序,从而提高软件开发效率.节约软件开发成本和维护成本. 各位代码界的大佬们总结出的七 ...

  6. MVC4 部署 could not load file or assembly system.web.http.webhost 或是其它文件出误

    自从VS2010发布之后使用它来做开发的程序员越来越多,其中很多人使用了MVC来作为新的开发框架,但是在系统部署的时候我们也遇到诸多问题,因为目前大多数windows服务器采用的还是Windows S ...

  7. js --装饰者模式

    定义 装饰者模式能够在补改变对象自身的基础上,在程序运行期间给对象动态的添加职责. 当看到装饰者模式的定义的时候,我们想到的js 的三大特性之一--继承,不也能够实现不改变对象自身的基础上,添加动态的 ...

  8. 【一起学源码-微服务】Netflix Eureka 源码一:Netflix Eureka 源码初探,我们为什么要读源码?

    前言 最近发现 网上好多自己的博客,很多朋友转载了文章却不加下 原载地址,本文欢迎转载一起学习,请在目录出加上原出处,感谢.转载来自:博客(一枝花算不算浪漫) 看了前面几篇文章的小伙伴知道,前几天在学 ...

  9. SpringBoot学习之@Configuration注解和@Bean注解

    @Configuration 1.@Configuration注解底层是含有@Component ,所以@Configuration 具有和 @Component 的作用. 2.@Configurat ...

  10. CentOS 6.5本地yum源、局域网离线yum仓库(断网情况下轻松安装各种依赖包)

    在工作中, 公司的服务器大部分都禁止连接外网的,初始化系统,测试某些产品时,往往缺一些软件或依赖包,一个个上传到机器,如此浪费时间,浪费金钱,en...yum能够自动查找并解决rpm包之间的依赖关系, ...