嗨,我为我的 ASP.NET MVC 应用程序编写了一个基于角色的自定义身份验证系统。
所以我所做的改变如下
在Global.asax.cs文件中添加了以下方法
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
try
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
if(!string.IsNullOrEmpty(username))
{
// user --> Roles Getting from DB using Stored Procdure
roles = user.RoleName;
}
e.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
throw;
}
}
}
}
catch (Exception)
{
throw;
}
}
在Web.Config中
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
在App_Start文件夹中的FilterConfig.cs
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
在登录控制器方法中
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginUserViewModel loginmodel, string returnUrl)
{
try
{
UserViewModel userdata=null;
if (loginmodel.UserName != null & loginmodel.Password != null)
{
// Get userData via Stored Procedure
if (userdata != null)
{
FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Dashboard", "Home");
}
}
else
{
ModelState.AddModelError("", "Login failed.");
}
}
else
{
ModelState.AddModelError("", "Login failed.");
}
return View(userdata);
}
catch (Exception)
{
throw;
}
}
Login.cshtml页面
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@* rest of data *@
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group ">
<div class="col-sm-12 col-lg-12 col-md-12">
<button type="submit" >Login</button>
</div>
</div>
}
最后在HomeController.cs
[Authorize(Roles="admin")]
public ActionResult Dashboard()
{
//rest of fetching
}
在这里一切正常,但不小心我在没有登录的情况下调试/运行仪表板视图页面,
现在我在文件中的FormsAuthentication_OnAuthenticate
方法中出现以下错误,Global.asax
你调用的对象是空的。
现在,当我开始调试这个项目时,它就在那里结束