我在global.asax中获得了以下代码,当用户未获得授权时显示错误信息:
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
Server.ClearError();
Response.Clear();
if (context.Response.StatusCode == 401)
{
context.Response.Write("You are not authorized.");
}
}
在RouteConfig.cs文件中,我有两个路由定义 - angular和test:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Test",
"test/{controller}/{action}"
);
routes.MapRoute(
name: "angular",
url: "{*.}",
defaults: new { controller = "Home", action = "Index" }
);
}
我使用角度路由 - ui路由器组件。
我没有显示关于用户未被授权的消息,而是希望将用户重定向到角度路由/状态"未自动化",我该如何实现?
下面的东西不会起作用:
Response.RedirectToRoute("not-autorized");
当我尝试重定向到这样的现有角度路线时:
context.Response.RedirectToRoutePermanent("angular");
我收到错误"此页面无法显示"。
当我添加如下:
context.Response.RedirectLocation = "/Home/Index";
然后我得到:401 unauthorized
这个,帖子转向了我的独白,我发现在获得Windows身份验证弹出窗口并且没有输入有效凭据后,Application_EndRequest不再被触发,因此重定向无法工作,该怎么办?
答案 0 :(得分:0)
您应该使用自定义授权属性,请参阅下文。
public class IsAuthenticated : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/AccessDenied");
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Home", action = "Index" }));
}
}
}
这将确保经过身份验证的用户将转到您的角度路由页面,其他人将路由到拒绝访问。
然后在每个要进行身份验证的控制器上使用该属性。例如:
[IsAuthenticated]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
现在您需要为拒绝访问的页面设置路由:
routes.MapRoute(
name: "AccessDenied",
url: "AccessDenied",
defaults: new { controller = "AccessDenied", action = "Index" });
routes.MapRoute(
name: "angular",
url: "{*.}",
defaults: new { controller = "Home", action = "Index" });
这需要高于默认的“angular”路线,因此实际上可以触发它。
为了安全起见,您的AccessDenied控制器设置属性[AllowAnonymous]
[AllowAnonymous]
public class AccessDeniedController : Controller
{
public ActionResult Index()
{
return View();
}
}
现在您可以自由创建AccessDenied页面了。