c#在WebAPI使用Session的方法
作者:天涯过者 时间:2023-07-07 23:20:10
最近在改写WebApp时要将以前用泛型处理例程写的Captcha 改成使用WebApi 来实作机制,在实作的过程中发现使用IRequiresSessionState session也无法使用(context.Session==null)
查过一些文章才发现需要在注册api路由需将RouteHandler 改写,才能使用。以下用ASP.net MVC 4来说明要实作的部分
建立HttpControllerHandler和HttpControllerRouteHandler 并覆写它
public class SessionRouteHandler : HttpControllerHandler, IRequiresSessionState
{
public SessionRouteHandler(RouteData routeData) : base(routeData)
{
}
}
public class SessionControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new SessionRouteHandler(requestContext.RouteData);
}
}
在WebApiConfig中将config.Routes.MapHttpRoute 改成
RouteTable.Routes.MapHttpRoute(using System.Web.Routing)并指定RouteHandler
public static void Register(HttpConfiguration config)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
).RouteHandler=new SessionControllerRouteHandler();
}
或者 在MVC的WebApi中默认是没有开启Session会话支持的。需要在Global中重写Init方法来指定会话需要支持的类型
public override void Init()
{
PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
或者:
public override void Init()
{
this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
base.Init();
}
在默认情况下是没有开启的。SessionStateBehavior有四个值:
Default使用默认ASP.NET逻辑来确定请求的会话状态行为。默认逻辑是寻找IHttpHandler中是否存在标记会话状态接口。
Disabled未启用会话状态来处理请求。 此设置将覆盖已通过检查请求的处理程序确定的任何会话行为。
ReadOnly为请求启用只读会话状态。这意味着会话状态无法更新。此设置将覆盖已通过检查请求的处理程序确定的任何会话状态行为。
Required为请求启用完全的读写会话状态行为。 此设置将覆盖已通过检查请求的处理程序确定的任何会话行为。
来源:http://www.cnblogs.com/tinya/p/4563641.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Springboot整个Quartz实现动态定时任务的示例代码
![](https://img.aspxhome.com/file/2023/9/78039_0s.png)
Unity UGUI实现简单拖拽图片功能
![](https://img.aspxhome.com/file/2023/9/77289_0s.jpg)
C#使用SharpZipLib压缩解压文件
实例讲解JAVA设计模式之备忘录模式
一文详解无痕埋点在Android中的实现
![](https://img.aspxhome.com/file/2023/3/137813_0s.jpg)
Unity使用鼠标旋转物体效果
![](https://img.aspxhome.com/file/2023/6/68616_0s.png)
50 道Java 线程面试题(经典)
C#中使用闭包与意想不到的坑详解
![](https://img.aspxhome.com/file/2023/8/116618_0s.png)
Java简化复杂系统调用的门面设计模式
![](https://img.aspxhome.com/file/2023/7/132107_0s.png)
Android7.0自动更新适配 包解析异常
Android如何使用圆形揭露动画巧妙地隐藏或显示View详解
Java动态 代理的应用详解
C# 拷贝数组的几种方法(总结)
SpringBoot项目没有把依赖的jar包一起打包的问题解决
Java实现单向链表的基本功能详解
![](https://img.aspxhome.com/file/2023/3/80213_0s.jpg)
java 微信随机红包算法代码实例
JAVA 内存溢出案例汇总
![](https://img.aspxhome.com/file/2023/7/61927_0s.jpg)
Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果
![](https://img.aspxhome.com/file/2023/5/129005_0s.gif)
详解jeefast和Mybatis实现二级联动的问题
![](https://img.aspxhome.com/file/2023/3/116823_0s.png)
Java面向对象程序设计:继承,多态用法实例分析
![](https://img.aspxhome.com/file/2023/4/79864_0s.png)