لماذا يقوم ActionFilterAttribute بإعادة التوجيه بعد تشغيل رمز الإجراء؟

StackOverflow https://stackoverflow.com/questions/3202191

سؤال

أحاول استخدام ActionFilterAttribute لإعادة توجيه المستخدمين الذين لم يقوموا بتسجيل الدخول.على الرغم من أن عملية إعادة التوجيه الخاصة بي تعمل، إلا أنها تقوم بإعادة التوجيه ولكنها تستدعي كل كود ActionResult الخاص بي أولاً.

هل هناك أي أفكار حول سبب عدم احترام العلم الحقيقي وإنهاء الرد؟

HttpContext.Current.Response.Redirect("~/Logon",true);

هذه هي نتيجة العمل الخاصة بي:

[RequireLoggedIn]
public ActionResult Create()
{
    return View(_MessageService.GetAllMessageCategories());
}

هذه هي صفتي:

public class RequireLoggedIn : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      if (Membership.GetUser() == null)
      {
           //Not logged in so back to the logon page.
           HttpContext.Current.Response.Redirect("~/Logon",true);
           HttpContext.Current.Response.End();
       }
    }
}
هل كانت مفيدة؟

المحلول

تحتاج إلى تعيين filterContext.Result إلى شيء غير فارغ لتجنب المعالجة النهائية، وإلا فلن تعرف MVC أن لديك دائرة كهربائية قصيرة.أبسط نهج سيكون فقط:

public override void OnActionExecuting(ActionExecutingContext filterContext) {
  if (Membership.GetUser() == null) {
       filterContext.Result = new RedirectResult("~/Logon");
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top