• 接口 ApiController调用Controller 模拟Session 封装


    原文: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);
    }
    
  • 相关阅读:
    many2many
    oneselfone
    one2one
    10-many2one
    08-one2many
    05-curd
    动态SQl
    文件系统缓存dirty_ratio与dirty_background_ratio两个参数区别
    expect用法举例
    通过命令修改mysql的提示符
  • 原文地址:https://www.cnblogs.com/guxingy/p/12875210.html
Copyright © 2020-2023  润新知