Using routing, URL redirection, and URL rewriting

When building applications, routing is used to map incoming requests to route handlers (URL matching) and to generate URLs for the responses (URL generation).

The routing capabilities of ASP.NET Core 3 combine and unify the routing capabilities of MVC and web API that have existed before. They have been rebuilt from the ground up to create a common routing framework with all of the various features in a single place, available to all types of ASP.NET Core 3 projects.

Now, let's look at how routing works internally to better understand how it can be useful in your applications and how to apply it to our Tic-Tac-Toe application example.

For each request received, a matching route is retrieved, based on the request URL. Routes are processed in the order they appear within the route collection.

To be more specific, incoming requests are dispatched to the corresponding handlers. Most of the time, this is done based on data in the URL, but you could also use any data in your requests for more advanced scenarios.

If you are using the MVC Middleware, you can define and create your routes in the Startup class, as shown at the beginning of the chapter. This is the easiest way to get started with URL matching and URL generation:

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

});

There is also a dedicated routing middleware that you can use for working with routing in your applications, which you have seen in the previous section on middleware. You just have to add it to the Startup class:

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

The following is an example of how to use it to call the UserRegistration service in the Startup class.

Firstly, we add UserService and routing to ServiceCollection:

    public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<IUserService, UserService>();
services.AddRouting();
}

Then we make use of them in the Configure method as follows:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ app.UseStaticFiles();
var routeBuilder = new RouteBuilder(app);
routeBuilder.MapGet("CreateUser", context =>
{ var firstName = context.Request.Query["firstName"];
var lastName = context.Request.Query["lastName"];
var email = context.Request.Query["email"];
var password = context.Request.Query["password"];
var userService = context.RequestServices.
GetService<IUserService>();
userService.RegisterUser(new UserModel { FirstName =
firstName, LastName = lastName, Email = email,
Password = password });
return context.Response.WriteAsync($"User {firstName} {lastName}
has been successfully created.");
});
var newUserRoutes = routeBuilder.Build();
app.UseRouter(newUserRoutes);
app.UseCommunicationMiddleware();
app.UseStatusCodePages("text/plain", "HTTP Error - Status Code:
{0}"); }

If you call it with some query string parameters, you will get the following result:

Another important middleware is the URL rewriting middleware. It provides URL redirection and URL rewriting functionalities. However, there is a crucial difference between both that you need to understand.

URL redirection requires a round-trip to the server and is done on the client-side. The client first receives a moved permanently 301 or moved temporary 302 HTTP status code, which indicates the new redirection URL to be used. Then, the client calls the new URL to retrieve the requested resource, so it will be visible to the client.

URL rewriting, on the other hand, is purely server-side. The server will internally retrieve the requested resource from a different resource address. The client will not know that the resource has been served from another URL as it is not visible to the client.

Coming back to the Tic-Tac-Toe application, we can use URL rewriting to give a more meaningful URL for registering new users. Instead of using UserRegistration/Index, we can use a much shorter URL, such as /NewUser:

    var options = new RewriteOptions() 
      .AddRewrite("NewUser", "/UserRegistration/Index", false); 
    app.UseRewriter(options);

Here, the user thinks that the page has been served from /NewUser, while, in reality, it has been served from /UserRegistration/Index without the user noticing:

This comes in handy for user experience on your application, when you want the URLs to be meaningful, and can play a part in search engine optimization, where it is important for the web crawlers to match what is in the URL and the page content.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.53.168