Search code examples
asp.net-coreasp.net-identity

Account/Login not found - identity


I am putting identity in my already created project, but it is not locating the Account/Login page.

enter image description here

It is not localizing the page, this is the controller:

[Route("[controller]/[action]")]
public class AccountController : Controller
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger _logger;

    public readonly Erp.Models.ErpDb _context;
    public AccountController(Erp.Models.ErpDb context, SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger)
    {
        _signInManager = signInManager;
        _logger = logger;
        _context = context;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout()
    {
        await _signInManager.SignOutAsync();
        _logger.LogInformation("User logged out.");
        return RedirectToPage("/Index");
    }
}

Startup

 public class Startup
{


    private IHostingEnvironment env;
    private IConfigurationRoot config;
    public Startup(IHostingEnvironment env)
    {

        this.env = env;
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        config = builder.Build();

    }

    public IConfiguration Configuration { get; }


    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ErpDb>(options => options.UseSqlServer("Data Source =servidor; Initial Catalog = ERP; User ID = sa; Password = password;Connect Timeout=30;"));

       services.AddMvc();

        services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ErpDb>()
    .AddDefaultTokenProviders();
        if (env.IsDevelopment())
            services.AddScoped<IMailService, DebugMailService>();

        else
            services.AddScoped<IMailService, MailService>();

        services.AddMvc().AddJsonOptions(jsonOptions =>
        {
            jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            jsonOptions.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        })
        .AddRazorPagesOptions(options =>
        {

            options.Conventions.AuthorizeFolder("/Account/Manage");
            options.Conventions.AuthorizePage("/Account/Logout");
            options.Conventions.AuthorizePage("/Details");

        });

        services.AddCors();
        services.AddDistributedMemoryCache();
        services.AddSession();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(config.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

        }

        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseSession();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=About}/{id?}");
        });
    }

Solution

  • Since you are using Razor pages for your account UI, you cannot have those .cshtml files inside the Views folder. The Views folder is only meant for views used by MVC but not Razor Pages.

    In order to have the framework pick those up with the correct URL, you need to move them to the Pages directory instead.

    Since you are then mixing Razor Pages and MVC in the same project (which is not a problem), you will have to adjust your layout setup in order to have both pick up the same layout file.

    Basically, you need to make sure that you have a _ViewStart.chtml file in both the Views and the Pages folder that configure the layout to use. If you previously used MVC, then you likely already have a Views/_ViewStart.cshtml. In that case, you need to also create a Pages/_ViewStart.cshtml file (you can copy it). The file should look like this:

    @{
        Layout = "_Layout";
    }
    

    Then, Razor Pages will also attempt to pick up the layout at Views/Shared/_Layout.cshtml, just like MVC does.