2012-04-28 32 views
0

新來SPA MVC4,試圖會話變量從賬戶控制器傳遞給LinqToEntitiesDataController通過識別用戶:LinqToEntitiesDataController MVC 4單頁應用 - Session變量

     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 

在此先感謝。

回答

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很適合sessionless。如此可擴展和REST原則。

LinqToEntitiesDataController路由添加在Custom AreaRegistration類(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() 
    )); 
如何

樣?

+0

謝謝,我仍然無法將該變量傳遞給Linq控制器,因爲它是一個部分類 – hncl 2012-04-29 02:40:36

+0

再次感謝,我仍然無法使用字符串phn = HttpContext.Current.Session [「PHN」]獲取會話變量的ToString();它仍然是空 – hncl 2012-05-01 16:11:09

+0

Hummmm.I沒有...在web.config中sessionState怎麼樣? – takepara 2012-05-02 05:38:55