[translation] ASP.NET How to redirect the core 2.0 web address

Time:2020-11-20

problem

How to ASP.NET URL redirection in core 2.0?

answer

Create an empty project in Startup.cs In the rewriter options, add the middleware URL:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

  var rewrite = new RewriteOptions()

    .AddRedirect("films", "movies")

    .AddRewrite("actors", "stars", true);

 

  app.UseRewriter(rewrite);

 

  app.Run(async (context) =>

  {

    var path = context.Request.Path;

    var query = context.Request.QueryString;

    await context.Response.WriteAsync($"New URL: {path}{query}");

  });

} 

Run, and enter: http://localhost : 56825 / films. Observe the redirection process through the client debugging tool

Enter: http://localhost : 56825 / actors, observe the redirection process again:

discuss

URL redirection is to modify the requested URL according to user-defined rules. The purpose is to unbind the server resources and browser address. This may be done for security reasons, search engine optimization (SEO), user-friendly web sites, redirecting HTTP to HTTPS, etc.

When you can’t use the redirection function of web server (IIS, Apache, nginx), ASP.NET Core provides an optional middleware for URL redirection. Then its performance and functionality are not comparable to web server redirection.

Redirection middleware can do two things: client redirection and server rewriting

Redirection (client)

This is a client operation, and the workflow is as follows:

1. The client requests a resource, such as / films

To indicate (2) the server’s address (302) in response to the request.

3. The client requests a new address and displays it in the address bar of the browser.

Rewrite (server)

It is a server-side operation, and the workflow is as follows:

1. The client requests a resource, such as / actors

2. The server maps its internal to a new address (such as / stars) and returns 200 (OK).

In this process, the client does not know the internal mapping operation of the server, so the browser address bar that the user sees still shows the original request address.

rule

Redirection and rewriting rules can be regular expressions. For more details, please refer to: https://docs.microsoft.com/en-gb/aspnet/core/fundamentals/url-rewriting

Custom redirection rules

We can also customize the redirection rules through a class inherited from the iRule interface

public class MoviesRedirectRule : IRule

{

  private readonly string[] _matchPaths;

  private readonly string _newPath;

 

  public MoviesRedirectRule(string[] matchPaths, string newPath)

  {

    _matchPaths = matchPaths;

    _newPath = newPath;

  }

 

  public void ApplyRule(RewriteContext context)

  {

    var request = context.HttpContext.Request;

 

    //It's already the target address. Return it directly

    if (request.Path.StartsWithSegments(new PathString(_newPath)))

    {

      return;

    }

 

    if (_matchPaths.Contains(request.Path.Value))

    {

      var newLocation = $"{_newPath}{request.QueryString}";

 

      var response = context.HttpContext.Response;

      response.StatusCode = StatusCodes.Status302Found;

      context.Result = RuleResult.EndResponse;

      response.Headers[HeaderNames.Location] = newLocation;

    }

  }

}

Then, in configure(), add the custom rule to rewriteoptions:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

  var rewrite = new RewriteOptions()

    .Add(new MoviesRedirectRule(

      matchPaths: new string[] { "/films", "/features", "/albums" },

      newPath: "/movies"));

 

 

  app.UseRewriter(rewrite);

 

  app.Run(async (context) =>

  {

    var path = context.Request.Path;

    var query = context.Request.QueryString;

    await context.Response.WriteAsync($"New URL: {path}{query}");

  });

}   

Run, enter: http://localhost : 56825 / films? Id = 123

Source code download

Original text: https://tahirnaushad.com/2017/08/18/url-rewriting-in-asp-net-core/

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.