Asp.net 允许匿名访问MVC4操作
我正在尝试允许匿名访问我的网站的根目录。如果我向site.com/home发出请求,它允许匿名访问。但是,如果我请求site.com/我会看到一个登录页面。到目前为止,我已经做了以下工作: 在web.config中,我为所有用户授权了“主页”:Asp.net 允许匿名访问MVC4操作,asp.net,asp.net-mvc-4,Asp.net,Asp.net Mvc 4,我正在尝试允许匿名访问我的网站的根目录。如果我向site.com/home发出请求,它允许匿名访问。但是,如果我请求site.com/我会看到一个登录页面。到目前为止,我已经做了以下工作: 在web.config中,我为所有用户授权了“主页”: <location path="Home"> <system.web> <authorization> <allow users="*" /> </
<location path="Home">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
我的主索引控制器操作如下所示:
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Zoom",
url: "zoom/{id}",
defaults: new { controller = "Zoom", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LoginAuthorize());
filters.Add(new HandleErrorAttribute());
}
我的路线如下所示:
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Zoom",
url: "zoom/{id}",
defaults: new { controller = "Zoom", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LoginAuthorize());
filters.Add(new HandleErrorAttribute());
}
这是通过一条路线完成的吗?我完全遗漏了什么吗?您必须在属性代码中实现逻辑来过滤它。换句话说,您必须检查并查看方法/类是否使用属性进行了注释,如果是,则跳过授权(或者针对您的场景进行相应的处理) 下面是一个例子:
/// <summary>
/// This class is used to ensure that a user has been authenticated before allowing a given method
/// to be called.
/// </summary>
/// <remarks>
/// This class extends the <see cref="AuthorizeAttribute"/> class.
/// </remarks>
public sealed class LoginAuthorize : AuthorizeAttribute
{
/// <summary>
/// The logger used for logging.
/// </summary>
private static readonly ILog Logger = LogManager.GetLogger(typeof(LoginAuthorize));
/// <summary>
/// Handles the authentication check to ensure user has been authenticated before allowing a method
/// to be called.
/// </summary>
/// <param name="filterContext">The authorization context object.</param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
DateTime methodEntryTime = DateTime.Now;
Helper.LogMethodEntry(Logger, MethodBase.GetCurrentMethod(), filterContext);
try
{
// determine if the called method has the AllowAnonymousAttribute, which means we can skip
// authorization
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (!skipAuthorization)
{
base.OnAuthorization(filterContext);
// make sure required session data is still present
if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Session[Helper.ROLE_NAME] as string))
{
HandleUnauthorizedRequest(filterContext);
}
}
Helper.LogMethodExit(Logger, MethodBase.GetCurrentMethod(), methodEntryTime);
}
catch (Exception e)
{
Helper.LogException(Logger, MethodBase.GetCurrentMethod(), e);
throw;
}
}
/// <summary>
/// Handles unauthorized requests. Redirects user to login page.
/// </summary>
/// <param name="filterContext">The authorization context object.</param>
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
DateTime methodEntryTime = DateTime.Now;
Helper.LogMethodEntry(Logger, MethodBase.GetCurrentMethod(), filterContext);
try
{
base.HandleUnauthorizedRequest(filterContext);
// redirect user to login page
filterContext.Result = new RedirectResult("~/Login");
Helper.LogMethodExit(Logger, MethodBase.GetCurrentMethod(), methodEntryTime);
}
catch (Exception e)
{
Helper.LogException(Logger, MethodBase.GetCurrentMethod(), e);
throw;
}
}
}
}
首先,您不应该对web.config使用Webforms授权方式。先把它处理掉。 其次,通过添加Authorize属性作为全局过滤器,您基本上是将Authorize属性应用于所有控制器和操作,这真的是您想要的吗? 更常见的是修饰动作方法或完整的控制器。如果控制器具有authorize属性,您仍然可以通过添加AllowAnonymous属性来允许匿名访问操作方法,就像您已经做的那样
使用这种方法应该可以很好地工作,路线看起来不错。尝试了您的建议,但如果我没有正确地实施,它将无法工作。如果它在我请求/主页时工作,那么将根请求发送到适当的控制器/操作不是问题吗?当我回家/回家时,它显示访问是正确的,因为它给出了正确的返回。您是否在OnAuthorization方法中设置了中断以确保它正常工作?我知道这种方法很有效,因为我正在我的一个生产应用程序中使用它。