لماذا يقوم ActionFilterAttribute بإعادة التوجيه بعد تشغيل رمز الإجراء؟
-
12-09-2020 - |
سؤال
أحاول استخدام 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");
}
}
لا تنتمي إلى StackOverflow