c#独自で作成した認証(Authorize)

C#において、ユーザーのログインを検証するためにカスタム認証(Authorize)を実装することができます。以下は簡単な例です:

最初に、System.Web.Mvc.AuthorizeAttributeクラスを継承したカスタムのAuthorizeAttributeクラスを作成してください。

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

それから、ログインの検証が必要なControllerやActionにCustomAuthorizeAttributeを使用してマーキングします。

[CustomAuthorize]
public class HomeController : Controller
{
    // 需要登录才能访问的Action
    public ActionResult Index()
    {
        return View();
    }

    // ...
}

例えば、ユーザーがログインしていない状態で、ログインが必要なアクションにアクセスしようとすると、ログインページにリダイレクトされます。一方、ユーザーがログイン済みの場合は、元々の認証ロジックが継続されます。

これは単なる簡単な例であり、具体的なニーズに合わせてカスタムされたログインの検証ロジックを作成することができます。

bannerAds