MVC 成员资格问题
几乎每次我运行 MVC 应用程序时,它都会在进入主页之前因错误而停止。
更新:这是最新的代码:
public class RequireLoggedIn : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Membership.GetUser() == null)
{
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);
}
为什么要这样做?过去它运作良好。
非常感谢任何帮助。
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() == null)
{
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在本示例中,我将添加一个属性来检查用户是否已登录。您根本不希望未经过身份验证的用户可以使用该操作,因此无需在操作本身的正文中对此进行管理。您可以使用
Authorize
来执行此操作,只是不以您正在使用的形式。也看看这个问题:ASP .NET MVC 中的 Authorize 属性是否用于身份验证和授权?
如果您想创建自定义属性(我建议这样做),则创建一个新属性ActionFilterAttribute
然后,您可以在整个应用程序中用它来装饰您的任何操作。简单:)
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
You can then decorate any of your Actions with this throughout your application. Simples :)
根据msdn,如果没有人登录,Membership.GetUser() 会引发异常。
http://msdn.microsoft.com/en-us/library/fcxcb339.aspx
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