简体   繁体   中英

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...

在此处输入图像描述

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?

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();

     });          
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM