您现在的位置是:网站首页> 编程资料编程资料
webapi跨域使用session的方法示例_实用技巧_
2023-05-24
403人已围观
简介 webapi跨域使用session的方法示例_实用技巧_
在之前的项目中,我们设置跨域都是直接在web.config中设置的。

这样是可以实现跨域访问的。因为我们这边一般情况下一个webapi会有多个网站、小程序、微信公众号等访问,所以这样设置是没有问题的。但是……如果其中一个网站需要用到cookie或者session的时候,
Access-Control-Allow-Origin如果还是设置成“*”就会报错,当然是前端报错。。。数据返回还有cookie/session都还是能存,但是报错就不爽了啊。
于是,想着整改一下。
先上前端代码。来个页面远程ajax请求去设置session。啥都没有,就是点按钮,发个请求。标记地方是必须加的
@{ ViewBag.Title = "TestSetSession"; } TestSetSession
@section scripts{ }然后再来个页面,获取上个页面设置的session。
@{ ViewBag.Title = "TestGetSession"; } TestGetSession
@section scripts{ }后台代码
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 { /// /// 设置session /// /// 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(1) }; HttpContext.Current.Response.Cookies.Add(cookie); return new { success = true, message = "设置session" }; } /// /// 获取session /// /// 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 } }; }结果:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- 如何利用HttpClientFactory实现简单的熔断降级_实用技巧_
- ASP.NET全栈开发教程之在MVC中使用服务端验证的方法_实用技巧_
- ASP.NET全栈开发教程之前后台校验结合详解_实用技巧_
- ASP.NET Core跨站登录重定向的实现新姿势_实用技巧_
- 基于.net core微服务的另一种实现方法_实用技巧_
- 基于.net standard 的动态编译实现代码_实用技巧_
- .Net Core项目如何添加日志功能详解_实用技巧_
- .Net Core Cors中间件的深入讲解_实用技巧_
- .net core xss攻击防御的方法_实用技巧_
- .Net Core2.1 WebAPI新增Swagger插件详解_实用技巧_
