Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c# - get values from class and method attribute in middleware in asp.net core

is it possible to get data from an attribute in middleware before the page is loaded? Meaning if I attach an attribute to a controller, can I access the data in middleware?

My for now empty attribute:

public sealed class Secure : Attribute
{
    public Secure()
    {

    }

    public Secure(params string[] roles)
    {

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you'd better custom ActionFilterAttribute to get the data before action excutes:

public class SecureAttribute : ActionFilterAttribute
{
    private readonly UserManager<ApplicationUser> _userManager;
    public SecureAttribute(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        //get data from query string
        if (context.ActionArguments.TryGetValue("returnUrl", out object value))
        {
            //returnUrl is the query string key name
            var query = value.ToString();
        }
        //get data from form
        if (context.ActionArguments.TryGetValue("test", out object model))
        {
            var data = model;  
        }
        //get data from log in User
        var USER = context.HttpContext.User;
        if(USER.Identity.IsAuthenticated)
        {
            var user =  _userManager.FindByNameAsync(USER.Identity.Name).Result;
            var roles = _userManager.GetRolesAsync(user).Result;
        }
        base.OnActionExecuting(context);
    }
}

Controller:

[ServiceFilter(typeof(SecureAttribute))]
public async Task<IActionResult> Index(string returnUrl)
{...}

[HttpPost]
[ServiceFilter(typeof(SecureAttribute))]
public IActionResult Index(Test test)
{
    return View(test);
}

Startup.cs:

services.AddScoped<SecureAttribute>();

If you use Identity to get the role,be sure register service like below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("YourConnectionString")));
   
    services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddScoped<SecureAttribute>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Result: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...