باسلام و عرض تبریک سال نو به همه برنامه نویسان
میخواستم بدونم چطور میتونم Override Authorize Attributeکنم به گونه ای که چک کنم ببین ایا کاربری که احراز هویت کرده به این اکشن در کنترلر دسترسی داره یا نه . لازم به ذکره که نام تمام کنترلر ها و تمام اکش های مربوط به کنترلر ها در دیتابیس ذخیره شده و باید یک کوئری روی دیتابیس انجام بشه
با تشکر و ارزوی موفقیت در سال جدید
شما میتونید از Permission استفاده کنید
نمونه زیر میتونه کمکتون کنه
ممنونم استاد مدائنی عزیز ولی من میخواستم نحوه Override کردن Authorize Attribute رو بدونم اگه بتونید یه مثال برم بنید ممنون میشم
public class OptionalAuthorizeAttribute : AuthorizeAttribute { private readonly bool _authorize; public OptionalAuthorizeAttribute() { _authorize = true; } public OptionalAuthorizeAttribute(bool authorize) { _authorize = authorize; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if(!_authorize) return true; return base.AuthorizeCore(httpContext); } }
public class MyAuthorizeAttribute: AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var authorized = base.AuthorizeCore(httpContext); if (!authorized) { // The user is not authorized => no need to go any further return false; } // We have an authenticated user, let's get his username string authenticatedUser = httpContext.User.Identity.Name; // and check if he has completed his profile if (!this.IsProfileCompleted(authenticatedUser)) { // we store some key into the current HttpContext so that // the HandleUnauthorizedRequest method would know whether it // should redirect to the Login or CompleteProfile page httpContext.Items["redirectToCompleteProfile"] = true; return false; } return true; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile")) { var routeValues = new RouteValueDictionary(new { controller = "someController", action = "someAction", }); filterContext.Result = new RedirectToRouteResult(routeValues); } else { base.HandleUnauthorizedRequest(filterContext); } } private bool IsProfileCompleted(string user) { // You know what to do here => go hit your database to verify if the // current user has already completed his profile by checking // the corresponding field throw new NotImplementedException(); } }
هیچ کاربری تا کنون از این پست تشکر نکرده است
با ما تماس بگیرید تا در این مسیر همراهتان باشیم :)