如何在 asp.net core 中获取自定义属性名称?

时间:2021-03-10 10:08:13

标签: asp.net asp.net-core attributes

我为操作名称创建了一个属性。我想在我的服务中获取属性名称。我尝试了很多解决方案,但它没有返回任何内容。 这是我的属性类:

public class CustomeAttribute : ActionFilterAttribute
{
    public string Name { get; set; }
}

这是我使用该属性的操作:

   [Custome(Name ="ُShow courses")]
    public IActionResult Index()
    {
        var course = _courseService.GetAllCourses();
        return View(course);
    }

这是我要返回属性名称的方法:

 public IList<ActionAndControllerName> AreaAndActionAndControllerNamesList(Assembly asm)
    {

        var contradistinction = asm.GetTypes()
            .Where(type => typeof(Controller).IsAssignableFrom(type))
            .SelectMany(type =>
                type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | 
       BindingFlags.Public))
            .Select(x => new
            {
                Controller = x.DeclaringType?.Name,
                //Action = x.Name,
                //Action=x.DeclaringType?.GetCustomAttributes(typeof(CustomeAttribute), false),
                // 
         
       Action=x.DeclaringType?.CustomAttributes.Where(c=>c.AttributeType==typeof(CustomeAttribute)),
                // Action=x.DeclaringType?.GetCustomAttributes(typeof(CustomeAttribute), false),
                // Action=x.DeclaringType?.CustomAttributes(typeof(CustomeAttribute), false),
                //Action=x.DeclaringType?.GetCustomAttribute(typeof(CustomeAttribute), false),
                Action=x.DeclaringType?.GetCustomAttributes<CustomeAttribute>(),
                //Action = x.DeclaringType?.GetCustomAttributes().Where(a => a.GetType() == 
          typeof(CustomeAttribute))
                Area = x.DeclaringType?.CustomAttributes.Where(c => c.AttributeType == 
           typeof(AreaAttribute)),
               
            });
        }

正如我所说,我尝试了上面评论的解决方案,但没有一个奏效。我该怎么办?

2 个答案:

答案 0 :(得分:0)

您可以尝试将 Name 保存到 ActionfilterAttribute 中的某个位置。以下是在 OnActionExecuting 方法中将数据保存到会话的演示:

测试控制器:

        SomeOtherClass _someOtherClass;
        public TestController(SomeOtherClass someOtherClass)
        {
            _someOtherClass = someOtherClass;
        }
        [Custome(Name = "Show courses")]
        public IActionResult TestActionFilterAttribute()
        {
            var Name = _someOtherClass.TestGet();
            return Ok();
        }

其他类:

public class SomeOtherClass
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private ISession _session => _httpContextAccessor.HttpContext.Session;

        public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string TestGet()
        {
            return _session.GetString("Custome_Name");
        }
    }

Startup.cs(IHttpContextAccessor 可以帮助获取外部控制器的seesion):

public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromDays(1);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<SomeOtherClass, SomeOtherClass>();


        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSession();

        ...
    }

客户属性:

public class CustomeAttribute: ActionFilterAttribute
    {
        public string Name { get; set; }
       

        public override void OnActionExecuting(ActionExecutingContext
                                           context)
        {
            if (Name != null) 
            {
                context.HttpContext.Session.SetString("Custome_Name", Name);
            }
      
        }


        public override void OnActionExecuted(ActionExecutedContext
                                              context)
        {
        }
    }

结果: enter image description here

答案 1 :(得分:0)

我找到了解决方案。我不应该在服务中使用“DeclaringType”。 这是解决方案:

var contradistinction = asm.GetTypes()
            .Where(type => typeof(Controller).IsAssignableFrom(type))
            .SelectMany(type =>
                type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | 
           BindingFlags.Public))
            .Select(x => new
            {
                Controller = x.DeclaringType?.Name,                  
                Action = x.GetCustomAttribute<CustomeAttribute>()?.Name,
                Area = x.DeclaringType?.CustomAttributes.Where(c => c.AttributeType == 
             typeof(AreaAttribute)),
            });