将UmbracoContext.Current的值变为null

时间:2016-02-11 18:47:05

标签: asp.net-mvc asp.net-mvc-4 umbraco umbraco7 umbraco6

我在Home Controller / Viewmodel类上有以下代码

public class HomeController : SurfaceController {
      ....


  [AllowAnonymous]   
public ActionResult LoginIn()  
 {
    var user = new UserDetail() { FirstName = "FirstName", LastName = "LastName" };
    UserDetailViewModel model = new UserDetailViewModel() { User = user };
    return PartialView("~/Views/Partials/__LoginPartial.cshtml", model);

  }
     ........ 
}

public class UserDetailViewModel : RenderModel
 {    
        public UserDetailViewModel() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
        public UserDetailViewModel(IPublishedContent content, CultureInfo culture) : base(content, culture) { }
        public UserDetailViewModel(IPublishedContent content) : base(content) { }
        public UserDetail User { get; set; } 
    }

以下是ActionExcuteFilter

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class ActionExcuteFilter : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.Current.Session == null || Convert.ToInt32(HttpContext.Current.Session["UserId"]) ==0)
        {
            var myAccountPage = uQuery.GetNodesByType("Login").FirstOrDefault();

            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
                { "action", "LoginIn" },
                { "controller", "Home" }});

        }
        base.OnActionExecuting(filterContext);
    } }

在主页上有以下链接

http://localhost/Products?categoryId=1这是指产品控制者的行动。

因此,如果用户登录,并点击链接一切正常。 (意思是说从UmbracoContext获取值并且各个页面都会被渲染)

但是当用户点击链接时没有登录麻烦启动(从UmbracoContext获取值时出错)

所以执行是:

产品控制器是电话> ActionExcuteFilter> RedirectToRouteResult> Home Controller> LoginIn Action> UserDetailViewModel>给出错误(将UmbracoContext.Current变为null)

所以我要做的是,当用户尝试访问页面..Product?categoryId = 1而无需登录时,他应该重定向到登录页面。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

如果您的UmbracoContext.Current为null,即使这种情况看起来很奇怪,也可以尝试使用此方法。 SurfaceController可能不需要非null的UmbracoContext。也许您应该重定向到RenderMvcController

 UmbracoContext.EnsureContext(new HttpContextWrapper(HttpContext.Current), 
                              ApplicationContext.Current,  true);