gpt4 book ai didi

asp.net-mvc - asp.net mvc 并检查用户是否已登录

转载 作者:行者123 更新时间:2023-12-03 18:10:54 61 4
gpt4 key购买 nike

我是 asp.net mvc 的新手,我需要检查用户是否在我的应用程序中登录,所以我将以下代码放在我的 global.asax 中

    void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;

string filePath= context.Request.FilePath;
string fileExtention = VirtualPathUtility.GetExtension(filePath);

// to skip request for static content like (.css or .js)
if (fileExtention == "")
{
if (filePath.ToLower() != "/account/login")
{
var user = (Utilisateur)context.Session["USER"];
if (user == null)
context.Response.Redirect(@"~/account/login");
}
}
}

我拦截每个传入请求以进行检查我想知道是否还有其他方法可以完成此类工作
并提前致谢。

最佳答案

你需要这样做吗?您应该检查是否可以使用 asp.net 身份验证、授权和成员资格提供程序。 (当您创建新的 ASP.NET MVC 3 应用程序时[当您选中“Internet 应用程序”时],它们会自动生成)。

然后,您可以对 Controller 和 Action 使用注解:(伪代码):
这仅允许授权用户访问 Controller (您甚至可以指定允许哪些用户或哪些角色):[Authorize(Roles = "Administrators")]

[Authorize]
controller{.....}

并检查用户是否已登录,已经有带有 Identity 属性的 User 属性。
此代码检查用户是否已通过身份验证(已登录):
controller...() {
...
if (User.Identity.IsAuthenticated) ...
...
}

关于asp.net-mvc - asp.net mvc 并检查用户是否已登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5484786/

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