我有一个ASP MVC 5网站,我有几个控制器和视图,如果没有通过if(User.Identity.Is)执行所有操作之前未经过身份验证,我如何将用户重定向到登录视图认证)
答案 0 :(得分:1)
装饰您的控制器(如果您希望该控制器中的所有操作都需要身份验证)或具有[Authorize]
属性的特定操作。您可以在web.config
文件中指定用户重定向到的登录URL。
[Authorize]
public class UserController : Controller
{
public ActionResult Index()
{
// Must be authorized
}
public ActionResult Users()
{
// Must be authorized
}
}
public class ProductController : Controller
{
public ActionResult Index()
{
// Doesn't require authorization
}
[Authorize]
public ActionResult Products()
{
// Must be authorized
}
}
进一步阅读:
http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx
答案 1 :(得分:0)
对于此任务,您可以使用[Authorize]属性,您可以在Class或Action级别实现该属性:
[Authorize]
public class AccountController : Controller
{
public AccountController () { . . . }
public ActionResult Register() { . . . }
public ActionResult Manage() { . . . }
public ActionResult LogOff() { . . . }
. . .
}
在上述实例中,尝试访问控制器中的任何操作方法会将用户重定向到登录页面,之后将进一步重定向到最初请求的操作。
有关如何使用自动调整属性的详细信息,请参阅MSDN article,因为它已展开示例和背景信息。
答案 2 :(得分:0)
回答1:
您可以在MVC中使用内置的[Authorize]
属性..
[Authorize]
public class YourController : Controller
{
public ActionResult YourAction()
{
}
}
[Authorize]
属性将检查用户是否经过身份验证,否则会自动将用户重定向到登录页面
回答2:
或者您可以将自定义过滤器属性设置为:
[AuthoriseUser]
public class YourController : Controller
{
public ActionResult YourAction()
{
}
}
public class AuthoriseUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Check user is authenticated
// if user is not authenticated then do as :
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Login", action = "Index" }));
}
}
回答3:
正如您在评论部分中所说的那样,您不想在项目中的每个控制器上编写[Authorize]
属性,那么以下答案将对您有所帮助:
public class YourController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
//....Check user authentication here
}
}
public class MyController : YourController
{
public ActionResult Myaction()
{
// ...
}
}
在上面的答案中,您所要做的就是制作自定义基本控制器YourController
,然后您可以将您的身份验证内容放在那里,然后您的网络应用中的每个控制器都会继承YourController
而不是内置基地Controller class
。
答案 3 :(得分:0)
您可以使用global.asax中的事件对每个请求进行身份验证和授权。
Application_AuthenticateRequest :当安全模块已将当前用户的身份建立为有效时触发。此时,用户的凭据已经过验证。
Application_AuthorizeRequest :在安全模块验证用户可以访问资源时触发。
所以,这样的事情(尽管这还不完整)
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
// you can re-direct them for example
}
}