接口 ApiController调用Controller 模拟Session 封装
2023-09-11 14:22:27 时间
原文:https://blog.csdn.net/qq_17255515/article/details/89338986
定义一个基类
public class BaseApiController : ApiController
{
/// <summary>
/// 返回一个带session的controller
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
[HttpGet]
public T GetController<T>() where T : System.Web.Mvc.Controller, new()
{
//模拟session
System.IO.TextWriter writer = new System.IO.StringWriter();
HttpRequest request = new HttpRequest("", "http://localhost:58059/Home/Index", "");
HttpResponse response = new HttpResponse(writer);
HttpContext context = new HttpContext(request, response);
var container = new System.Web.SessionState.HttpSessionStateContainer(
"",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
20000,
true,
HttpCookieMode.UseCookies,
SessionStateMode.Off,
false
);
SessionStateUtility.AddHttpSessionStateToContext(context, container);
var userInfo = (User as FormsPrincipal).UserData;
context.Session.Add("userid", userInfo.userid);
context.Session.Add("user", userInfo.user);
context.Session.Add("Created", userInfo.Created);
context.Session.Add("pwd", userInfo.pwd);
context.Session.Add("userModel", userInfo.userModel);
HttpContextBase httpContext = new HttpContextWrapper(context);
T t = new T();
System.Web.Mvc.ControllerContext controllerContext = new System.Web.Mvc.ControllerContext();
controllerContext.HttpContext = httpContext;
t.ControllerContext = controllerContext;
return t;
}
}
在ApiController中的使用
[HttpGet, TokenAuthorize]
public IHttpActionResult GetSessionInfo()
{
HomeController controller = GetController<HomeController>();
var d = controller.GetSession().Data;
return Json<dynamic>(d);
}
相关文章
- 数组模拟栈和队列
- poj 3617 Best Cow Line 贪心模拟
- 【2017.12.02普及组模拟】花生采摘
- Java实现蓝桥杯模拟递增三元组
- Java实现蓝桥杯模拟带九9的数的个数
- [转]使用java简单模拟ping和telnet的实现
- scrapy框架使用-模拟登陆,使用cookie登陆,使用post登陆,使用selenium模拟登陆
- Qt编写的项目作品34-雷达模拟仿真工具(雨田哥作品)
- Scala模拟Spark分布式计算流程示例代码
- 新冠病毒传播模拟(Matlab实现)
- 使用numpy模拟torch.fft.fft拯救paddle
- INetSim模拟C2 这玩意比起nc来说更专业!
- 基于Edgar-Guevara-Codina的有限差分光束传输法matlab仿真模拟
- QQ 静态截图程序模拟实现 之 URL记录