由于您的观点得到了Razor视图引擎在服务器端渲染到HTML代码,您可能会注意到没有区别。具体而言,两种方法的主要区别在于,如果第一种方法在发生错误或抛出异常的情况下不安全,这会导致丑陋的错误页面和低效的异常处理。
这是而后一种方法可以看作是最好的,因为它可以让你处理所有异常或错误的控制器,或者更重要的是,你可以根据用户的角色使你返回的视图。
例如:
[CustomAuthorize]
public IActionResult AdminDashboard(){
if(HttpContext.User.IsInRole("Admin"))
return View("X");
else if (HttpContext.User.IsInRole("Guest"))
return View("Y");
else
return RedirectToAction("Some Action");
// Or throw an exception
}
,此外,你可以写一个异常处理属性来处理渲染后的结果,当在控制器级别或抛出异常。这可以通过继承Attribute
并实现IActionFilter
和IResultFilter
接口来完成。
例如:
public class HandleLoginAttribute : Attribute, IActionFilter, IResultFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception != null) {
// Handle exceptions thrown by the action api
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
public void OnResultExecuted(ResultExecutedContext context)
{
if (context.Exception != null)
{
// Handle exceptions thrown when rendering the view
}
}
public void OnResultExecuting(ResultExecutingContext context)
{
}
}
所以,你可以有这样的:
[HandleLogin]
[CustomAuthorize]
public IActionResult AdminDashboard(){
if(HttpContext.User.IsInRole("Admin"))
return View("X");
else if (HttpContext.User.IsInRole("Guest"))
return View("Y");
else
return RedirectToAction("Some Action");
}
而且主要优点是可以有效地重用所有这些,而你不能做(或者你不能有效地做)里面的意见。
第二种方法是标准方法。 –
假设您将来会获得新角色。然后,这个角色将与方法1自动获得管理员访问权限。在这种情况下,白名单总是比黑名单更好,因此做的方法2. – LSA
你从哪里获得'role id'? – oldbam