Phyzia
Phyzia

Reputation: 13

Problem with Razor pages routing to default pages

When I try to access the index.cshtml page under /Pages/Home directory using the url /Home or /Home/index an internal redirection always happens to the index.cshtml pages under the directory /Pages.

Another case if i use URL /Home/Home i can access the index.cshtml page under /Pages/Home successfully and no redirection happens.

Here is the Project structure

enter image description here

Startup Class Configure

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<ErrorHandlerMiddleware>();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
            app.UseHttpsRedirection();
        }

        app.UseFileServer();
        app.UseSession();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseRequestLocalization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages().RequireAuthorization();
     

        });
    }

Configure Services

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddAntiforgery(o => o.HeaderName = xHeaderName);
        services.AddDataReposiotry();
        services.AddBackOfficeServices();
        services.AddDbContext<DigitalServiceContext>(options => options.UseSqlServer(Configuration.GetConnectionString(ConnectionString)));

        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = xLoginPath;
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
            options.ExpireTimeSpan = TimeSpan.FromHours(1);
        });
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(cookieOptions =>
        {
            cookieOptions.LoginPath = xLoginPath;
            cookieOptions.Cookie.Name = "DSINTRANET";
            cookieOptions.Cookie.IsEssential = true;
        });
        services.AddHttpClient();
        //services.AddLocalization(options => options.ResourcesPath = "Resources");
        services
           .AddMvc()
           .AddViewLocalization()
           .AddDataAnnotationsLocalization(options =>
           {
               options.DataAnnotationLocalizerProvider = (type, factory) =>
               {
                   var assemblyName = new AssemblyName(typeof(CommonResources).GetTypeInfo().Assembly.FullName);
                   return factory.Create(nameof(CommonResources), assemblyName.Name);
               };
           });

        var cultures = new CultureInfo[]
        {
            new CultureInfo("en"),
            new CultureInfo("ar"),
        };
        services.AddRazorPages(options =>
        {
            options.RootDirectory = "/Pages";
            options.Conventions.AddFolderApplicationModelConvention(
                "/Workflow",
                model => model.Filters.Add(new VerfiySessionDataAttribute(Configuration)));
            options.Conventions.AddFolderApplicationModelConvention(
                "/Home",
                model => model.Filters.Add(new VerfiySessionDataAttribute(Configuration)));
            options.Conventions.AddFolderApplicationModelConvention(
                "/Dashboard",
                model => model.Filters.Add(new VerfiySessionDataAttribute(Configuration)));
        })
        .AddExpressLocalization<CommonResources>(ops =>
        {
            ops.ResourcesPath = "Resources";
            ops.RequestLocalizationOptions = o =>
            {
                o.SupportedCultures = cultures;
                o.SupportedUICultures = cultures;
                o.DefaultRequestCulture = new RequestCulture("en");
            };
        });
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(double.Parse(Configuration["Session:IdleTimeout"]));
        });
        services.AddMemoryCache();
        services.Configure<FormOptions>(x => x.MultipartBodyLengthLimit = 5368709120);
        AddMapperProfile(services, Configuration);
    }

Any Idea what could be the issue here ?

Upvotes: 0

Views: 888

Answers (2)

Tupac
Tupac

Reputation: 2910

Razor Pages conventions are configured using an AddRazorPages overload that configures RazorPagesOptions in Startup.ConfigureServices.

Route order Routes specify an Order for processing (route matching).

Route processing is established by convention:

1.Routes are processed in sequential order (-1, 0, 1, 2, … n).

2.When routes have the same Order, the most specific route is matched first followed by less specific routes.

3.When routes with the same Order and the same number of parameters match a request URL, routes are processed in the order that they're added to the PageConventionCollection.

Specific examples can be found in the official documents:

Razor Pages route and app conventions in ASP.NET Core

Upvotes: 1

Serge
Serge

Reputation: 43860

Index in a root directory is always default page. To change it add a new root directory

ConfigureServices(IServiceCollection services)
{

.......

    services.AddRazorPages()
    .AddRazorPagesOptions(options => {
        options.RootDirectory = "/Home";
    });

......

}

Upvotes: 0

Related Questions