我正在尝试ASP.NET MVC中的以下场景。我想构建一个简单的MVC应用程序,我想创建一个自定义IAuthorizationFilter,它应该只执行一个SQL语句来检查用户是否存在。如果用户存在,则继续,否则重定向到不同的视图。
我为自定义过滤器创建了一个新类:
public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.Controller.ViewBag.AutherizationMessage = "Custom Authorization: Message from OnAuthorization method.";
}
}
在我想检查用户的操作中,我添加了过滤器:
[CustomAuthorizationAttribute]
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
在视图中,我添加了输出值:
<div>
@ViewBag.AutherizationMessage
</div>
通常,当我执行解决方案并执行操作时,我会按预期在网站上收到消息。
但是我知道一个真实世界的场景,如何以及在何处实施检查以及如何重定向未授权?
答案 0 :(得分:0)
1.创建自定义Authorize属性,如下所述: 2.在您的控制器中创建一个处理无效用户的操作(如下例中的Home Controller中的Restricted action,此操作只返回一个视图)
public class CustomAuthorize : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Restricted" }));// Create an Action name "Restricted" in your home controller or call whatever action you need to call.
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated
return false;
}
string user = HttpContext.Current.User.Identity.Name;
bool isUser = IsAppUser(user);
return isUser;
}
private bool IsAppUser(string user)
{
//Check existence of your user and return true or false as per the condition
}
}
现在,只要您需要,就可以在您的操作中使用此自定义授权属性。希望这能帮助你:)