【发布时间】:2016-10-20 07:22:18
【问题描述】:
您好,我为我的 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
}
这里一切正常,但不小心我在没有登录的情况下调试/运行仪表板视图页面,
现在我在Global.asax 文件中的FormsAuthentication_OnAuthenticate 方法中出现以下错误,
对象引用未设置为对象的实例。
现在,当我开始调试这个项目时,它就在那里结束
【问题讨论】:
-
FormsAuthentication_OnAuthenticate内的哪一行抛出对象引用异常?似乎一个变量试图从其他对象分配空引用。 -
@TetsuyaYamamoto 出现错误,如关注 i.imgur.com/jJb18Mi.png
标签: c# asp.net-mvc asp.net-mvc-4 form-authentication custom-authentication