C# Custom Authentication with Authorize
In C#, you can validate user login through custom authentication using Authorize. Here is a simple example:
To begin with, create a custom AuthorizeAttribute class that inherits from the System.Web.Mvc.AuthorizeAttribute class.
using System.Web;
using System.Web.Mvc;
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// 检查用户是否已经登录
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
// 未登录,重定向到登录页面
filterContext.Result = new RedirectResult("~/Account/Login");
}
else
{
// 已登录,继续执行原有的授权逻辑
base.OnAuthorization(filterContext);
}
}
}
Next, use CustomAuthorizeAttribute to mark the Controller or Action that requires login verification.
[CustomAuthorize]
public class HomeController : Controller
{
// 需要登录才能访问的Action
public ActionResult Index()
{
return View();
}
// ...
}
In the example above, if a user is not logged in and tries to access an Action that requires login, they will be redirected to the login page. If the user is already logged in, the original authorization logic will continue to be executed.
This is just a simple example. You can customize the login verification logic based on specific needs.