开发者

MVC Membership Problem

Almost every time I run my MVC app, it stops with errors before getting to the home page.

UPDATE: Here's the latest code:

public class RequireLoggedIn : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Membership.GetUser() == nul开发者_如何学Cl)
            {
                filterContext.Result = new RedirectResult("~/Logon");
            }
        }
    }

    public ActionResult Index()
    {
        MembershipUser myObject = Membership.GetUser();
        Guid UserID = (Guid)myObject.ProviderUserKey;

        DateTime dateTime = new DateTime();
        dateTime = DateTime.Now.AddDays(14);

        var model = db.Task.Where(n => (n.UserId == UserID) && (n.Completed == false) && (n.Due < dateTime));
        return View(model);

    }

Why is it doing this? It has worked fine in the past.

Any help is much appreciated.


I would add an attribute to check the user is logged in for this example. You don't want the action to be available for non authenticated users at all so there is no need to manage this in your body of your action itself. You can use Authorize to do this just not in the form you are using it.

Check out this question too: Is the Authorize attribute in ASP .NET MVC used for Authentication as well as Authorization?

If you want to create a custom attribute, which I would recommend, then create a new ActionFilterAttribute

public class RequireLoggedIn : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext) {
      if (Membership.GetUser() == null) {
        filterContext.Result = new RedirectResult("~/Logon");
       }
  }
}

You can then decorate any of your Actions with this throughout your application. Simples :)


According to msdn Membership.GetUser() throws an exception if you don't have anyone logged in.

http://msdn.microsoft.com/en-us/library/fcxcb339.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜