gpt4 book ai didi

asp.net - 允许匿名访问 MVC4 操作

转载 作者:行者123 更新时间:2023-12-04 05:12:24 25 4
gpt4 key购买 nike

我试图允许匿名访问我网站的根目录。如果我向 site.com/home 提出请求,它允许匿名访问。但是,如果我请求 site.com/,我会看到一个登录页面。到目前为止,我已经完成了以下工作:

在 web.config 中,我为所有用户授权了“主页”:

  <location path="Home">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>

在 FilterConfig.cs 中,我添加了以下 AuthorizeAttribute:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}

我的 Home Index Controller 操作如下所示:
    [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 }
);

这是通过路线完成的吗?我完全错过了什么吗?

最佳答案

您必须在属性代码中实现逻辑才能对其进行过滤。换句话说,您必须检查并查看方法/类是否使用该属性进行了注释,如果是,则跳过授权(或针对您的场景进行相应处理)。

下面是一个例子:

    /// <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;
}
}
}
}

然后,在 Global.asax你会添加这个 LoginAuthorize类,像这样:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LoginAuthorize());
filters.Add(new HandleErrorAttribute());
}

关于asp.net - 允许匿名访问 MVC4 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14735787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com