原文: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);
}