Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core 2 Routing without MVC

I am trying to create a simple .Net Core 2 application with an Angular front end and an api/db backend.

I do not want to use MVC, since I have no need for typical dot net Views or Models, but I am having trouble serving my index.html files and also routing the api calls to my controller.

I know it's somewhere in the program.cs and involving the routes, but I have been having trouble finding documentation on how to do what I want without using the mvc package.

Simply, here are my requirements again:

  1. Serve my angular index.html file when routing to the root (let angular handle the rest of the routes there)
    1. Route my /api routes to be routed to a c# dot net controller
    2. Not to use MVC

Thanks!

like image 810
blubberbo Avatar asked Mar 07 '23 19:03

blubberbo


1 Answers

You can use the the UseRouter() middleware to explicitly map routes directly as part of your application configuration pipeline.

For example, the following creates a custom route to handle Lets Encrypt requests which by default would fail if any other routing is enabled. The following code goes into the Configure() method of the server's Startup class:

        // Handle Lets Encrypt Route(before MVC processing!)
        app.UseRouter(r =>
        {
            r.MapGet(".well-known/acme-challenge/{id}", async (request, response, routeData) =>
            {
                var id = routeData.Values["id"] as string;
                var file = Path.Combine(env.WebRootPath, ".well-known", "acme-challenge", id);
                await response.SendFileAsync(file);
            });
        });

This essentialy makes it very easy to simple routing scenarios or forward requests to other handlers.

Note that this is a raw interface that doesn't include any input or output handling beyond the raw Request/Response semantics.

If you are doing anything with API style data, then I would still recommend using MVC and controllers which handle all sorts of things that you'd otherwise have to build yourself. In Core, API and MVC run the same Controller pipeline so you can think of MVC as Web API and MVC combined.

For most common use cases using MVC is still the way to go. The above approach is great for micro-services or one off requests as that might buy you a little bit of a performance gain since it doesn't have to load any of the MVC bits or fire into that pipeline, but you're responsible for doing your own serialization and request processing.

like image 54
Rick Strahl Avatar answered Mar 27 '23 15:03

Rick Strahl