ASP.NET MVC AllowAnonymous 属性不起作用
ASP.NET MVC AllowAnonymous attribute not working
AllowAnonymous
属性在我的 MVC 项目中根本不起作用 (目标框架 4.7).
我已经尝试了互联网上的所有方法,但仍然总是被重定向到登录页面。
连我都试过了:
我究竟缺少什么?
这是我的控制器:
using OnDemand.Helper;
using System.Web.Mvc;
namespace OnDemand.Controllers
{
[App_Auth.AllowAnonymous]
[System.Web.Mvc.AllowAnonymous]
public class AdminDashboardController : Controller
{
private readonly DashboardHelper _dashboardHelper;
public AdminDashboardController()
{
_dashboardHelper = new DashboardHelper();
}
[App_Auth.AllowAnonymous] // Not Working
[System.Web.Mvc.AllowAnonymous] // Not Working
public ActionResult Index()
{
return View(_dashboardHelper.DashboardData());
}
}
}
过滤器配置:
using System.Web.Mvc;
using OnDemand.App_Auth;
namespace OnDemand.App_Start
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new SessionExpireAttribute()); //check session expire and redirect to login
}
}
}
全局 asax class:
using OnDemand.App_Start;
using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace OnDemand
{
public class MvcApplication : HttpApplication
{
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Session_Start()
{
Session.Timeout = 24 * 60; // return 24 hours
}
}
}
自定义 Authorize
和 AllowAnonymous
属性 classes:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace OnDemand.App_Auth
{
public class AuthorizeAccessAttribute : AuthorizeAttribute
{
private readonly int code;
public AuthorizeAccessAttribute(int code)
{
this.code = code;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var hasAccess = false;
if (httpContext.Session["Roles"] == null) return false;
if (SectionsAndFeatures.HasAccess(code, httpContext.Session["Roles"] != null ? httpContext.Session["Roles"].ToString() : string.Empty))
{
hasAccess = true;
}
return hasAccess;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "UnauthorizedAccess" },
{ "controller", "Home" },
{ "area", "" }
}); //new HttpUnauthorizedResult("You are not authorized.");
}
}
public class AllowAnonymousAttribute : AuthorizeAttribute
{
public AllowAnonymousAttribute()
{
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool IsAuthenticAttribute =
(filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) &&
filterContext.HttpContext.User.Identity.IsAuthenticated;
if (!IsAuthenticAttribute)
{
base.OnAuthorization(filterContext);
}
}
}
}
网页配置:
<location path="AdminDashboard/Index">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
为什么不按标准方式使用它呢?没有重复或自定义属性的简单 AllowAnonymous 属性。
[AllowAnonymous]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
}
public ActionResult Logout()
{
}
}
或者在您的代码中:
using OnDemand.Helper;
using System.Web.Mvc;
namespace OnDemand.Controllers
{
[AllowAnonymous]
public class AdminDashboardController : Controller
{
private readonly DashboardHelper _dashboardHelper;
public AdminDashboardController()
{
_dashboardHelper = new DashboardHelper();
}
[AllowAnonymous]
public ActionResult Index()
{
return View(_dashboardHelper.DashboardData());
}
}
}
我发现我们使用的是自定义方法,我只需要在该列表中包含我的控制器名称:
public static List<string> ByPassController()
{
try
{
return new List<string>
{
"Access",
"InterpreterSelection",
"Language",
"Log",
"CallBack",
"Controller",
"IvrOnDemand",
"Main",
"CallDetail",
"ConferenceParticipant",
"DashBoardData",
"CallWaitingResponse",
"IVRRejoinParticipant",
"IVRAuto",
"OnDemand",
"Assignment",
"SilentListenCallback",
"AutoOnDemand",
"StelCallLogs",
"DialOut",
"AdminDashboard",
"Developer"
};
}
catch (Exception ex)
{
LogWriter.ErrorLogWriter(nameof(CommonFunction), nameof(ByPassController), ex.Message);
return new List<string>();
}
}
AllowAnonymous
属性在我的 MVC 项目中根本不起作用 (目标框架 4.7).
我已经尝试了互联网上的所有方法,但仍然总是被重定向到登录页面。
连我都试过了:
我究竟缺少什么?
这是我的控制器:
using OnDemand.Helper;
using System.Web.Mvc;
namespace OnDemand.Controllers
{
[App_Auth.AllowAnonymous]
[System.Web.Mvc.AllowAnonymous]
public class AdminDashboardController : Controller
{
private readonly DashboardHelper _dashboardHelper;
public AdminDashboardController()
{
_dashboardHelper = new DashboardHelper();
}
[App_Auth.AllowAnonymous] // Not Working
[System.Web.Mvc.AllowAnonymous] // Not Working
public ActionResult Index()
{
return View(_dashboardHelper.DashboardData());
}
}
}
过滤器配置:
using System.Web.Mvc;
using OnDemand.App_Auth;
namespace OnDemand.App_Start
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new SessionExpireAttribute()); //check session expire and redirect to login
}
}
}
全局 asax class:
using OnDemand.App_Start;
using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace OnDemand
{
public class MvcApplication : HttpApplication
{
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Session_Start()
{
Session.Timeout = 24 * 60; // return 24 hours
}
}
}
自定义 Authorize
和 AllowAnonymous
属性 classes:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace OnDemand.App_Auth
{
public class AuthorizeAccessAttribute : AuthorizeAttribute
{
private readonly int code;
public AuthorizeAccessAttribute(int code)
{
this.code = code;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var hasAccess = false;
if (httpContext.Session["Roles"] == null) return false;
if (SectionsAndFeatures.HasAccess(code, httpContext.Session["Roles"] != null ? httpContext.Session["Roles"].ToString() : string.Empty))
{
hasAccess = true;
}
return hasAccess;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "UnauthorizedAccess" },
{ "controller", "Home" },
{ "area", "" }
}); //new HttpUnauthorizedResult("You are not authorized.");
}
}
public class AllowAnonymousAttribute : AuthorizeAttribute
{
public AllowAnonymousAttribute()
{
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool IsAuthenticAttribute =
(filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) &&
filterContext.HttpContext.User.Identity.IsAuthenticated;
if (!IsAuthenticAttribute)
{
base.OnAuthorization(filterContext);
}
}
}
}
网页配置:
<location path="AdminDashboard/Index">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
为什么不按标准方式使用它呢?没有重复或自定义属性的简单 AllowAnonymous 属性。
[AllowAnonymous]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
}
public ActionResult Logout()
{
}
}
或者在您的代码中:
using OnDemand.Helper;
using System.Web.Mvc;
namespace OnDemand.Controllers
{
[AllowAnonymous]
public class AdminDashboardController : Controller
{
private readonly DashboardHelper _dashboardHelper;
public AdminDashboardController()
{
_dashboardHelper = new DashboardHelper();
}
[AllowAnonymous]
public ActionResult Index()
{
return View(_dashboardHelper.DashboardData());
}
}
}
我发现我们使用的是自定义方法,我只需要在该列表中包含我的控制器名称:
public static List<string> ByPassController()
{
try
{
return new List<string>
{
"Access",
"InterpreterSelection",
"Language",
"Log",
"CallBack",
"Controller",
"IvrOnDemand",
"Main",
"CallDetail",
"ConferenceParticipant",
"DashBoardData",
"CallWaitingResponse",
"IVRRejoinParticipant",
"IVRAuto",
"OnDemand",
"Assignment",
"SilentListenCallback",
"AutoOnDemand",
"StelCallLogs",
"DialOut",
"AdminDashboard",
"Developer"
};
}
catch (Exception ex)
{
LogWriter.ErrorLogWriter(nameof(CommonFunction), nameof(ByPassController), ex.Message);
return new List<string>();
}
}