0

SPA MVC4 的新手,尝试将会话变量从帐户控制器传递给 LinqToEntitiesDataController,以通过以下方式识别用户:

                      using (DALEntities db = new DALEntities())
                        {
                            string PHN = (from p in db.Patients
                                          where p.UserName == model.UserName
                                          select p.PHN).First();
                            Session["P"] = PHN;
                        }

在 LinqToEntitiesDataController 我尝试使用如下变量:

public partial class DALController : LinqToEntitiesDataController<MyVDC.Models.DALEntities>
    {
        public IQueryable<MyVDC.Models.TestModel> GetTestModel()
        {
            **string phn = (string)Session["P"];**
            return ObjectContext.TestModels.Where(b => b.PHN == phn).OrderBy(b => b.ID);

        }
}

我得到这个错误:

The name 'Session' does not exist in the current context

这是唯一的方法,还是有更好的方法来使用这个控制器的会话变量。

我还尝试在帐户控制器中使用:

 HttpContext.Current.Session["P"] = PHN;

但我得到这个错误:

'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found 

提前致谢。

4

1 回答 1

0
public class SessionHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
    {
        return new SessionHttpControllerHandler(requestContext.RouteData);
    }
}

public class SessionHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
{
    public SessionHttpControllerHandler(RouteData routeData) : base(routeData) { }
}

创建会话支持HttpControllerHandler,并在Global.asax中路由入口这个类。

    routes.Add("SessionApis",
        new HttpWebRoute(
            url: "api/{controller}/{id}",
            defaults: new RouteValueDictionary(new {id = RouteParameter.Optional}),
            routeHandler: new SessionHttpControllerRouteHandler()
    ));

但是,我认为 ApiController 很适合无会话使用。如此可扩展和 REST 原则。

LinqToEntitiesDataController 路由添加在自定义区域注册类(DALRouteRegistration 类?)。更改脚手架默认区域寄存器代码。

    RouteTable.Routes.MapHttpRoute(
        "DAL", // Route name
        "api/DAL/{action}", // URL with parameters
        new { controller = "DAL" } // Parameter defaults
    );

    RouteTable.Routes.Add("SessionDALApis",
        new HttpWebRoute(
            url: "api/DAL/{action}",
            defaults: new RouteValueDictionary(new { controller = "DAL" }),
            routeHandler: new SessionHttpControllerRouteHandler()
    ));

这个怎么样?

于 2012-04-28T15:14:17.540 回答