User.IsInRole() 在中间件中始终为 false

我有一个简单的中间件类:


    public class RouterMiddleware {

    private readonly RequestDelegate _next;


    public RouterMiddleware(RequestDelegate next)

    {

        this._next = next;

    }


    public async Task Invoke(HttpContext context)

    {


        if (!context.User.IsInRole("Guest"))

        {

            await _next.Invoke(context);

            return;

        }


        if (context.Request.Path.StartsWithSegments("/home/") 

            || context.Request.Path.StartsWithSegments("/api/profile/")

        {

                await _next.Invoke(context);

        }

        else

        {

            context.Response.Redirect("/home/");

            return;

        }

    }


}

并context.User.IsInRole("Guest")在任何情况下为任何角色返回 false。有什么方法可以检查中间件类中的用户角色吗?


宝慕林4294392
浏览 191回答 1
1回答

互换的青春

问题出在Startup.cs.&nbsp;中间件的顺序是:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;app.UseMiddleware<Middleware.RouterMiddleware>(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;app.UseAuthentication();但必须是:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;app.UseAuthentication(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;app.UseMiddleware<Middleware.RouterMiddleware>();
打开App,查看更多内容
随时随地看视频慕课网APP