【问题标题】:ASP.Net core 3.1 website not redirecting when unauthorized未经授权时,ASP.Net core 3.1 网站不​​重定向
【发布时间】:2021-07-27 19:10:00
【问题描述】:

我有一个带有身份和 2 个页面的 ASP.Net 核心 3.1 应用程序:索引和私有(需要授权)。 当我直接浏览到私人页面时,我希望应用程序将我重定向到登录页面。 然而,浏览器却显示 {"message":"Unauthorized"}。 该消息来自哪里,为什么没有重定向到登录?

(导航到登录 /Identity/Account/Login 直接会显示登录页面)

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<BackendUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();


        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = $"/Identity/Account/Login";
            options.LogoutPath = $"/Identity/Account/Logout";
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
        app.UseStatusCodePages();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

    }
}

控制器

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult Private()
    {
        return View();
    }
   
}

【问题讨论】:

  • 如果你删除app.UseStatusCodePages会发生什么?
  • 同样没有 app.UseStatusCodePages

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


【解决方案1】:

我无法重现您的问题。您的项目可能还有另一个问题。例如,您正在使用一些中间件。

无论如何,请尝试注销并重新登录或清除浏览器cookie,因为登录过程会向浏览器添加cookie以识别身份验证。这将更新所有损坏的 cookie,并且可能会解决授权问题。

【讨论】:

  • 我的错。 [Authorize] 属性是指导致此行为的自定义属性。
猜你喜欢
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 2017-04-12
  • 1970-01-01
  • 2020-07-09
  • 2012-01-23
  • 1970-01-01
相关资源
最近更新 更多