我的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>主页控制器> LoginIn Action> UserDetailViewModel>给出错误(将UmbracoContext.Current设置为null)

所以我想做的是,当用户尝试不登录而访问页面..Product?categoryId = 1时,应将其重定向到登录页面。

提前致谢 :)

最佳答案

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

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

关于asp.net-mvc - 将UmbracoContext.Current的值获取为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35347565/

10-15 05:42