首页 技术 正文
技术 2022年11月14日
0 收藏 318 点赞 4,435 浏览 2747 个字

在之前的项目中,我们设置跨域都是直接在web.config中设置的。

webapi跨域使用session

这样是可以实现跨域访问的。因为我们这边一般情况下一个webapi会有多个网站、小程序、微信公众号等访问,所以这样设置是没有问题的。但是……如果其中一个网站需要用到cookie或者session的时候,

Access-Control-Allow-Origin如果还是设置成“*”就会报错,当然是前端报错。。。数据返回还有cookie/session都还是能存,但是报错就不爽了啊。

于是,想着整改一下。

先上前端代码。来个页面远程ajax请求去设置session。啥都没有,就是点按钮,发个请求。标记地方是必须加的

@{
ViewBag.Title = "TestSetSession";
}<h2>TestSetSession</h2><button onclick="Set()">设置session</button>@section scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function Set() {
$.ajax({
url: "http://localhost:1338/api/Test/SetSession?session=1234567fdsdfghjhgfds",
dataType: "json",
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: {},
type: "post",
success: function (data) {
alert(data.message)
},
error: function () {
alert('服务器发生错误!');
}
});
}
</script>
}

然后再来个页面,获取上个页面设置的session。

@{
ViewBag.Title = "TestGetSession";
}<h2>TestGetSession</h2>
<button onclick="Get()">获取session</button>@section scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function Get() {
$.ajax({
url: "http://localhost:1338/api/Test/GetSession",
dataType: "json",
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: {},
type: "get",
success: function (data) {
alert("session:" + data.data.session_state + ",cookie:" + data.data.cookie);
},
error: function () {
alert('服务器发生错误!');
}
});
}
</script>
}

后台代码

1.先允许webapi使用session

在global中加入如下代码

        public override void Init()
{
PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
} void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(
System.Web.SessionState.SessionStateBehavior.Required);
}

2.允许跨域。我这里使用的是Microsoft.AspNet.WebApi.Cors

先安装包,然后在WebApiConfig中加入如下代码。等同于在web.config中设置

            //允许跨域
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

在请求方法上打上[EnableCors]标签,特指某一些域名的访问需要cookie/session

    [EnableCors("http://localhost:6477,http://localhost:6478", "*","*")]
public class TestController : ApiController
{
/// <summary>
/// 设置session
/// </summary>
/// <returns></returns>
public dynamic SetSession(string session)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
//缓存state
HttpContext.Current.Session["session_test"] = session;
HttpCookie cookie = new HttpCookie("cookie_test")
{
Value = session,
Expires = DateTime.Now.AddHours()
};
HttpContext.Current.Response.Cookies.Add(cookie);
return new
{
success = true,
message = "设置session"
};
} /// <summary>
/// 获取session
/// </summary>
/// <returns></returns>
public dynamic GetSession()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
var session = HttpContext.Current.Session["session_test"];
HttpCookie _cookie = HttpContext.Current.Request.Cookies["cookie_test"];
var cookie = _cookie?.Value??"";
string session_state = session == null ? "" : session.ToString();
return new
{
success = true,
message = "获取session",
data = new { session_state, cookie }
};
}

结果:

webapi跨域使用session

webapi跨域使用session

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295