.NET 7 and UseEndPoints()
Asked Answered
P

4

29

I am trying to convert a .NET Core 3.1 project to .NET 7.

When I use this in my Program.cs class:

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

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

It gives me this message:

Suggest using top level route registrations UseEndpoints

Then, I clicked on Show potential fixes in Visual Studio and it suggests this:

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

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Which looks the same to me.

In .NET 7, what should I do if I need to use RazorPages()?

Thanks!

Pyosis answered 5/12, 2022 at 16:47 Comment(0)
T
33

AFAIK it should work as is but the warning suggests to register the routes at the top-level of a minimal hosting application, i.e.:

app.MapRazorPages();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

See the ASP0014: Suggest using top level route registrations code analysis rule.

Terrel answered 5/12, 2022 at 18:27 Comment(2)
Oh ok, so I don't need UseEndpoints and I can just change endpoints.MapControllerRoute to app.MapControllerRoute ? Thanks!Pyosis
@Pyosis yes, exactly.Terrel
S
1

This is what I am using for using endpoints.

  app.UseEndpoints(endpoints =>
  {
      endpoints.MapControllerRoute(
             name: "areas",
             pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
      endpoints.MapControllerRoute(
              name: "default",
              pattern: "{controller=Home}/{action=Index}/{id?}");
      endpoints.MapRazorPages();
  });

I hope that helps.

Stationmaster answered 16/12, 2023 at 19:30 Comment(2)
Well actually not really. This question has a good answer. Your answer is just showing the same case the OP originally had.Spectroscope
There is a difference in the API used and the order of things that matters. I am using Endppoints on app not MapControl on app also the areas should be before the default, and in my case I am showing MapRazor at the end not at first. What was suggested was the ideal way in earlier versions before UseEndpoint was introduced.Stationmaster
G
1

You can use just like that for .net core 8

app.MapControllerRoute(
               name: "areas",
               pattern: "{area:exists}/{controller}/{action}/{id?}");
app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
Gardas answered 29/6 at 9:42 Comment(0)
S
1

For healthchecks you can use this:

    app.UseRouting();
    app.UseHealthChecks("/health");
    app.UseHealthChecks("/health/ping", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("ping")
    });
Studio answered 23/7 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.