0

この問題があります。ユーザーがログインすると、formsauthanticationticket を使用して Cookie を作成します。

var formAuthTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(1), false, "");
                    var encryptedFormAuthTicket = FormsAuthentication.Encrypt(formAuthTicket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedFormAuthTicket);
                    Response.Cookies.Add(cookie);
                    return RedirectToAction("Index", "Home");

今。PreRequestHandlerExecute イベントで、ユーザーが認証されているかどうか、Cookie が存在するかどうかを確認します。

var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (cookie != null)
        {

            var formAuthTicket = FormsAuthentication.Decrypt(cookie.Value);
            var newFormAuthTicket = new FormsAuthenticationTicket(formAuthTicket.Version, formAuthTicket.Name,
                                                                    formAuthTicket.IssueDate,
                                                                    DateTime.Now.AddMinutes(1),
                                                                    formAuthTicket.IsPersistent,
                                                                    formAuthTicket.UserData,
                                                                    FormsAuthentication.FormsCookiePath);
            cookie.Value = FormsAuthentication.Encrypt(newFormAuthTicket);
            context.Response.Cookies.Set(cookie);
        }

しかし、クッキーが存在しない/期限切れの場合、ユーザーがリンクをクリックしたときに、ユーザーをログインページにリダイレクトしたいと考えています。何か案が?ありがとう

編集

Authorize属性が使えないからです。私はそれについて知っています。Webプロジェクトで参照されているアセンブリにhttpmoduleがあります。httpmodule には、PreRequestHandlerExecute() イベントを初期化する Init メソッドがあります。イベントでは、ユーザーの認証を確認します。「else」でこのようなものを使用すると-> Response.Redirect(url)、サイクルリダイレクトが発生しますが、それは間違っています。リクエストなしで 10 分後、ユーザーが何らかのリンクをクリックすると、ログイン ページにリダイレクトされます -> それは私の問題です。解決できません。

4

1 に答える 1

1

なぜ[Authorize]属性を使用しないのですか?アクションのサインに追加され、認証に関連する Cookie の有効期限が切れた場合、自動的にログイン ページにリダイレクトされます

例えば

[Authorize]
public ActionResult Profile()    
{
}

また、カスタム実装を作成する必要がある場合は、カスタム属性を作成して、たとえばインターフェイスを実装します

public class FooAuthorizeAttribute : AuthorizeAttribute
{
     public string fooField{ get; set; }

public override void OnAuthorization(AuthorizationContext filterContext)
{
    //Do my stuff
}

次に、アクションで呼び出されます

[FooAuthorizeAttribute]
public ActionResult Profile()    
{
}
于 2012-08-10T14:36:02.420 に答える