سؤال

أحاول إضافة تفويض إلى وحدات التحكم الخاصة بي ولا يعمل ...

لست متأكدًا من أين ننظر في برنامجي ، ولكن إضافة

[Authorize] 

لا يعمل التصفية في وحدة التحكم الخاصة بي ، ناهيك عن أي شيء مثل

[Authorize(Roles = "Manager")]

لقد تمكنت من الحصول على هذا العمل في التطبيق الافتراضي الذي يتم توفيره عند إنشاء مشروع MVC جديد (أي ، أتمكن لنفترض أنني أزعجت أشياء على طول الطريق عندما قمت ببناء تطبيقي. هل يعرف أي شخص أين يجب أن أتطلع لإصلاح هذا؟ لدي مستخدمون ولديهم أدوار ؛ أنا أستخدم مخطط ASP.NET الذي تم إنشاؤه تلقائيًا ؛ لقد درست ملف الويب الخاص بي. ليس لدي أدنى فكرة لماذا لا تعمل مرشحات التفويض الخاصة بي.؟.

هل كانت مفيدة؟

المحلول

كتبت سمة مخصصة لحل هذه المشكلة. يمكنك أن تنسب أساليب وحدة التحكم الخاصة بك على النحو التالي:

[RequiresRole(Role="Admin")]
public ActionResult Index()
{
    int i = 5 + 5;

    return View();
}

رمز السمة كما يلي ....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Web.Controllers
{
    public class RequiresRoleAttribute : ActionFilterAttribute
    {
        public string Role { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (string.IsNullOrEmpty(Role))
            {
                throw new InvalidOperationException("No role specified.");
            }

            string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
            string redirectUrl = string.Format("?returnUrl={0}", redirectOnSuccess);
            string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.HttpContext.Response.Redirect(loginUrl, true);
            }
            else
            {
                bool isAuthorised = filterContext.HttpContext.User.IsInRole(this.Role);
                if (!isAuthorised)
                {                        
                    filterContext.HttpContext.Response.Redirect(loginUrl, true);
                }                
            }  
        }      
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top