我想添加一个简单的登录。因此,我认为最好的方法是将凭据添加到数据库中,然后查询该凭据以及您是否登录了用户名和密码。这是有效的,它会查询数据库,然后您会登录并重定向到家。然后我尝试通过 url 访问 home 并注意到我可以在不登录的情况下做到这一点。所以我想我应该使用
[Authorize]
Home Controller 上的属性,因为我不希望未经授权的用户访问它,因此应该将其重定向回登录页面。这不起作用。当我在控制器上使用授权时,我在应用程序中收到错误。
Object reference not set to an instance of an object.
在 web.config 中,它看起来像这样:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="2880" /> <-- I have changed the login url to my login controller.
</authentication>
我的登录控制器是这样的。
public ActionResult Index(UserModel model) <-- I query the db in the model.
{
if (!ModelState.IsValid)
{
return View(model);
}
if(!model.IsAdmin(model.UserName, model.Password))
{
ModelState.AddModelError("username", "you are not a admin");
return View(model);
}
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
那么如何正确使用这个 Authorize 属性呢?我什至可以按照我使用它的方式使用它吗?我在 web.config 中遗漏了什么吗?问候!
对此进行了一些更新。由于它不起作用,我将其添加到 web.config 中:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="5">
</forms>
</authentication>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear/>
<add name="MyMembershipProvider" type="MyNamespace.MyMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
userIsOnlineTimeWindow="2"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
以及具有硬编码凭据的会员提供者:
public class MyMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (username.Equals("user", StringComparison.CurrentCultureIgnoreCase) && password.Equals("myPassword"))
return true;
else
return false;
}
然后我尝试用这样的 Authorization 属性装饰我的 HomeController:
[Authorize()]
public class HomeController : Controller
{}
但仍然得到同样的错误。我的意思是我可以登录,但是当我到达“主页”时,我得到了和以前一样的错误。这到底是什么名字?!这有什么线索吗?!
问候!