Share via

Placing Routes in Multiple Files/Folders Using Minimal API in .Net 6

Ryan Vinson 21 Reputation points
2021-12-07T02:20:16.307+00:00

To Whom Can Answer:

Most examples show the .NET 6 Minimal API with builder, services, classes and routes all in Program.cs.

  • Is it possible to declare routes in other files and folders within an "ASP.NET Core Web API" project?
  • Can routes like "app.MapGet("/", () => "Hello World!");" exist outside of Program.cs?

For a single instance of Kestrel

If possible, how...
What are the best practices for large projects?

Thank you,
Ryan

Developer technologies | ASP.NET Core | Other
0 comments No comments

Answer accepted by question author

  1. AgaveJoe 31,361 Reputation points
    2021-12-07T12:53:56.517+00:00

    The standard pattern is writing an extension method for the IApplicationBuilder to add the middleware, routing in this case, to the pipeline.

    Middleware extension method

    ASP.NET Core Middleware

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points
    2021-12-07T16:27:09.507+00:00

    you can create an external module that is called from program.cs passing the IApplicationBuilder.

    AddMyApplicationRoutes(app);

    or as suggested make it an extension:

    app.AddMyApplicationRoutes();

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Ryan Vinson 21 Reputation points
    2021-12-08T00:21:18.277+00:00

    This is a working example of what I interpreted from the above suggestions.
    In a file called SomethingRegistration.cs:

    namespace Something.Apis
    {
        public static class SomethingRegistrationExtension
        {
            public static IApplicationBuilder UseSomethingRegistration( this IApplicationBuilder builder )
            {
                return builder.UseEndpoints(endpoints =>
                {
                    endpoints.MapPost("/authenticate", async context => await context.Response.WriteAsync("Reject Something") );
    
                    endpoints.MapGet("/confuse/{id}", async context => await context.Response.WriteAsync("Good-Bye World!!!!") );
                });
            }
        }
    }
    

    I called it from Program.cs as follows:

    ...
    app.UseRouting();
    
    app.UseSomethingRegistration(); // <-- My routes in another file/folder
    
    app.MapGet( "/", () => "Hello World!" );
    
    app.Run();
    

    Thanks everyone!

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.