2011-09-09 7 views
0

ASP.NET MVC 블로그를 사용하여 쿠키가 사용 된 클라이언트 시간대의 게시물 및 주석 날짜를 표시하기 위해 쿠키에 클라이언트 시간대 오프셋이 포함되어 있습니다. 서버가 요청을 받으면 쿠키에서 오프셋 값을 읽고 브라우저에 보내기 전에 그에 따라 모든 날짜를 변경합니다. 내 질문에 대한 모든 요청에 ​​전역 변수에 쿠키를 저장할 수 있도록 어떻게 날짜 조정을 위해 액세스 할 수 있습니다. 당신이 다음 세션을 필요로 할 때마다 액세스 할 수 있습니다 쿠키마다asp.net mvc의 전역 변수에 쿠키 값 저장

session["MyVarName"] = mycookievalue 

을 사용하지 않으려면

답변

0

당신은 세션 변수를 사용할 수 있습니다.

또한 e 커스텀 모델 바인더를 구현하여 세션의 가치를 모델에 바인딩 할 수 있다고 생각할 수도 있습니다. (예 : 클래스 UserSettingsModel)

1

일반적으로 컨트롤러 및 동작이 많을수록 외부에서 제공되는 값에 따라 테스트 가능하고 견고한 단위가됩니다. 나는 모델 바인더를 만든 다음

public class ClientTimeZoneSettings 
{ 
    public string TimeZoneName {get; set;} // or whatever 
} 

시간대

에 대한 설정을 보유하고 모델을 만들고, 이런 식

우선 할 것입니다. 그 모델 결합제의 Global.asax에

보호를 위해 Application_Start 공극() { AreaRegistration.RegisterAllAreas()이 모델 바인더 등록 쿠키

public class ClientTimeZoneSettingsModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (controllerContext.RequestContext.HttpContext.Request.Cookies.AllKeys.Contains("timeZoneName")) 
     { 
      bindingContext.Model = new ClientTimeZoneSettings {TimeZoneName = controllerContext.RequestContext.HttpContext.Request.Cookies["timeZoneName"]; } 
     } 

    } 
} 

로부터 값을 추출하기 위해 사용된다;

RegisterGlobalFilters(GlobalFilters.Filters); 
RegisterRoutes(RouteTable.Routes); 


ModelBinders.Binders.Add(typeof(ClientTimeZoneSettings), new ClientTimeZoneSettingsModelBinder()); 

}

그리고 주요 포인트. 크게 간단한 방법 :

이 nuget에서 MvcFutures를 설치하는 설정을 필요로하는 모든 행동에서 직접

public ActionResult ShowComments(ClientTimeZoneSettings settings) 
{ 
    // use settings 
} 

UPDATE 매개 변수로 ClientTimeZoneSettings를 사용할 수 있습니다. 모델 바인딩시 쿠키 값을 자동으로 검사하는 CookieValueProviderFactory이 포함되어 있습니다. 그것을 사용하려면 ValueProviderFactories

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 

    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 

    ValueProviderFactories.Factories.Add(new CookieValueProviderFactory()); 
} 

에 추가 한 다음 쿠키 이름에 accorting 당신의 매개 변수의 이름을

public ActionResult ShowComments(string timeZoneName) 
{ 
    // timeZoneName will contain your cookie value 
    return View(); 
}