AliKhansari
AliKhansari

Reputation: 89

Asp.net Core 3.1- How can I return from Controller to Razor Page?

I want when the user is logged in to the site, Go to the address I want in razor pages...

  if (rolename == "User")
       {            
        return RedirectToPage("Dashboard","Profile");
       }

This code did not work correctly ...

enter image description here

Here is the error message:

InvalidOperationException: The relative page path 'Dashboard' can only be used while executing a Razor Page. Specify a root relative path with a leading '/' to generate a URL outside of a Razor Page. If you are using LinkGenerator then you must provide the current HttpContext to use relative pages.

how can do this?

Upvotes: 1

Views: 1525

Answers (1)

Rena
Rena

Reputation: 36585

RedirectToPage have multiple methods with different parameter,what you did relate to the following method:

        //
    // Summary:
    //     Redirects (Microsoft.AspNetCore.Http.StatusCodes.Status302Found) to the specified
    //     pageName using the specified pageHandler.
    //
    // Parameters:
    //   pageName:
    //     The name of the page.
    //
    //   pageHandler:
    //     The page handler to redirect to.
    //
    // Returns:
    //     The Microsoft.AspNetCore.Mvc.RedirectToPageResult.
    [NonAction]
    public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler);

In your case,it should be:

return RedirectToPage("/Profile/Dashboard");

Also,be sure add razor pages routing:

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddRazorPages(); 
 }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
        //...

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

         endpoints.MapRazorPages();

     });          
 }

Upvotes: 3

Related Questions