asp net core middleware redirect

Redirect Non WWW to WWW using Asp.Net Core Middleware

On an ASP.Net Core application startup I have:

When in Production I need to redirect all Non WWW to WWW Urls

How can I do this using Rewrite Middleware?

I think this can be done using AddRedirect and Regex:

9 Answers 9

A reusable alternative would be to create a custom rewrite rule and a corresponsing extension method to add the rule to the rewrite options. This would be very similar to how AddRedirectToHttps works.

Future versions of the rewrite middleware will contain the rule and the corresponding extension method. See this pull request

I’m more of an Apache user and fortunately URL Rewriting Middleware in ASP.NET Core provides a method called AddApacheModRewrite to perform mod_rewrite rules on the fly.

2- then call it this way:

Using just a regex,

It’s unclear from if what AddRedirect method does and if it actually accepts regex.

But to insert a «www» to a url without «www»?
You could try it with these strings:

Because of the negative lookahead (?!www[.]) after the protocol, it’ll ignore strings like http://www.what.ever

I think instead of using Regex unless it is a must you can use the Uri class to reconstruct your url

And the result will look like

Since ASP.NET Core 3.0 (2019) these methods can be used:

Example

Here’s a regex to try:

It will select URLs like:

I would then approach the replacement with something like the following:

Источник

ASP.NET Core Middleware

Middleware is software that’s assembled into an app pipeline to handle requests and responses. Each component:

Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

Request delegates are configured using Run, Map, and Use extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it’s called a terminal middleware because it prevents further middleware from processing the request.

Migrate HTTP handlers and modules to ASP.NET Core middleware explains the difference between request pipelines in ASP.NET Core and ASP.NET 4.x and provides additional middleware samples.

Create a middleware pipeline with IApplicationBuilder

The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. The following diagram demonstrates the concept. The thread of execution follows the black arrows.

Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.

The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. This case doesn’t include an actual request pipeline. Instead, a single anonymous function is called in response to every HTTP request.

Chain multiple request delegates together with Use. The next parameter represents the next delegate in the pipeline. You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate, as the following example demonstrates:

When a delegate doesn’t pass a request to the next delegate, it’s called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work. For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline. Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke statements. However, see the following warning about attempting to write to a response that has already been sent.

Don’t call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started throw an exception. For example, setting headers and a status code throw an exception. Writing to the response body after calling next :

HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.

Run delegates don’t receive a next parameter. The first Run delegate is always terminal and terminates the pipeline. Run is a convention. Some middleware components may expose Run[Middleware] methods that run at the end of the pipeline:

If you would like to see code comments translated to languages other than English, let us know in this GitHub discussion issue.

In the preceding example, the Run delegate writes «Hello from 2nd delegate.» to the response and then terminates the pipeline. If another Use or Run delegate is added after the Run delegate, it’s not called.

Middleware order

The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and Razor Pages apps. You can see how, in a typical app, existing middlewares are ordered and where custom middlewares are added. You have full control over how to reorder existing middlewares or inject new custom middlewares as necessary for your scenarios.

The Endpoint middleware in the preceding diagram executes the filter pipeline for the corresponding app type—MVC or Razor Pages.

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

The following Startup.Configure method adds security-related middleware components in the typical recommended order:

In the preceding code:

In some scenarios, middleware has different ordering. For example, caching and compression ordering is scenario specific, and there’s multiple valid orderings. For example:

With the preceding code, CPU could be saved by caching the compressed response, but you might end up caching multiple representations of a resource using different compression algorithms such as Gzip or Brotli.

The following ordering combines static files to allow caching compressed static files:

The following Startup.Configure method adds middleware components for common app scenarios:

In the preceding example code, each middleware extension method is exposed on IApplicationBuilder through the Microsoft.AspNetCore.Builder namespace.

UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.

Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. The Static File Middleware provides no authorization checks. Any files served by Static File Middleware, including those under wwwroot, are publicly available. For an approach to secure static files, see Static files in ASP.NET Core.

If the request isn’t handled by the Static File Middleware, it’s passed on to the Authentication Middleware (UseAuthentication), which performs authentication. Authentication doesn’t short-circuit unauthenticated requests. Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.

The following example demonstrates a middleware order where requests for static files are handled by Static File Middleware before Response Compression Middleware. Static files aren’t compressed with this middleware order. The Razor Pages responses can be compressed.

For Single Page Applications (SPAs), the SPA middleware UseSpaStaticFiles usually comes last in the middleware pipeline. The SPA middleware comes last:

For more details on SPAs, see the guides for the React and Angular project templates.

Forwarded Headers Middleware order

Forwarded Headers Middleware should run before other middleware. This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing. To run Forwarded Headers Middleware after diagnostics and error handling middleware, see Forwarded Headers Middleware order.

Branch the middleware pipeline

Map extensions are used as a convention for branching the pipeline. Map branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.

The following table shows the requests and responses from http://localhost:1234 using the previous code.

Request Response
localhost:1234 Hello from non-Map delegate.
localhost:1234/map1 Map Test 1
localhost:1234/map2 Map Test 2
localhost:1234/map3 Hello from non-Map delegate.

When Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request.

Map supports nesting, for example:

Map can also match multiple segments at once:

MapWhen branches the request pipeline based on the result of the given predicate. Any predicate of type Func can be used to map requests to a new branch of the pipeline. In the following example, a predicate is used to detect the presence of a query string variable branch :

The following table shows the requests and responses from http://localhost:1234 using the previous code:

Request Response
localhost:1234 Hello from non-Map delegate.
localhost:1234/?branch=main Branch used = main

Built-in middleware

ASP.NET Core ships with the following middleware components. The Order column provides notes on middleware placement in the request processing pipeline and under what conditions the middleware may terminate request processing. When a middleware short-circuits the request processing pipeline and prevents further downstream middleware from processing a request, it’s called a terminal middleware. For more information on short-circuiting, see the Create a middleware pipeline with IApplicationBuilder section.

Additional resources

Middleware is software that’s assembled into an app pipeline to handle requests and responses. Each component:

Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

Request delegates are configured using Run, Map, and Use extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it’s called a terminal middleware because it prevents further middleware from processing the request.

Migrate HTTP handlers and modules to ASP.NET Core middleware explains the difference between request pipelines in ASP.NET Core and ASP.NET 4.x and provides additional middleware samples.

Create a middleware pipeline with IApplicationBuilder

The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. The following diagram demonstrates the concept. The thread of execution follows the black arrows.

Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.

The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. This case doesn’t include an actual request pipeline. Instead, a single anonymous function is called in response to every HTTP request.

The first Run delegate terminates the pipeline.

Chain multiple request delegates together with Use. The next parameter represents the next delegate in the pipeline. You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate, as the following example demonstrates:

When a delegate doesn’t pass a request to the next delegate, it’s called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work. For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline. Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke statements. However, see the following warning about attempting to write to a response that has already been sent.

Don’t call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started throw an exception. For example, changes such as setting headers and a status code throw an exception. Writing to the response body after calling next :

HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.

Middleware order

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

The following Startup.Configure method adds security related middleware components in the recommended order:

In the preceding code:

The following Startup.Configure method adds middleware components for common app scenarios:

In the preceding example code, each middleware extension method is exposed on IApplicationBuilder through the Microsoft.AspNetCore.Builder namespace.

UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.

Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. The Static File Middleware provides no authorization checks. Any files served by Static File Middleware, including those under wwwroot, are publicly available. For an approach to secure static files, see Static files in ASP.NET Core.

If the request isn’t handled by the Static File Middleware, it’s passed on to the Authentication Middleware (UseAuthentication), which performs authentication. Authentication doesn’t short-circuit unauthenticated requests. Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.

The following example demonstrates a middleware order where requests for static files are handled by Static File Middleware before Response Compression Middleware. Static files aren’t compressed with this middleware order. The MVC responses from UseMvcWithDefaultRoute can be compressed.

Use, Run, and Map

Configure the HTTP pipeline using Use, Run, and Map. The Use method can short-circuit the pipeline (that is, if it doesn’t call a next request delegate). Run is a convention, and some middleware components may expose Run[Middleware] methods that run at the end of the pipeline.

Map extensions are used as a convention for branching the pipeline. Map branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.

The following table shows the requests and responses from http://localhost:1234 using the previous code.

Request Response
localhost:1234 Hello from non-Map delegate.
localhost:1234/map1 Map Test 1
localhost:1234/map2 Map Test 2
localhost:1234/map3 Hello from non-Map delegate.

When Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request.

MapWhen branches the request pipeline based on the result of the given predicate. Any predicate of type Func can be used to map requests to a new branch of the pipeline. In the following example, a predicate is used to detect the presence of a query string variable branch :

The following table shows the requests and responses from http://localhost:1234 using the previous code.

Request Response
localhost:1234 Hello from non-Map delegate.
localhost:1234/?branch=main Branch used = main

Map supports nesting, for example:

Map can also match multiple segments at once:

Источник

Разбираемся с middleware в ASP.NET Core

А пока делимся с вами традиционным полезным переводом.

Этой статья раскрывает концепции Middleware в ASP.NET Core. К концу этой статьи вы получите четкое представление о следующих моментах:

Что такое Middleware?

Почему порядок расположения Middleware имеет значение?

Методы Run, Use и Map.

Как создать собственное Middleware?

Как реализовать просмотр каталогов с помощью Middleware?

Что такое Middleware?

Middleware (промежуточное или связующее программное обеспечение) — это фрагмент кода в конвейере приложения, используемый для обработки запросов и ответов.

Например, у нас может быть middleware-компонент для аутентификации пользователя, middleware-компонент для обработки ошибок и еще один middleware-компонент для обслуживания статических файлов, таких как файлы JavaScript, CSS, разного рода изображения и т. д.

На рисунке ниже показано, как запрос обрабатывается middleware-компонентами.

Как правило, каждое middleware обрабатывает входящие запросы и передает выполнение следующему middleware для дальнейшей обработки.

Но middleware-компонент также может решить не вызывать следующую часть middleware в конвейере. Это называется замыканием (short-circuiting) или завершением конвейера запросов. Замыкание зачастую желательно, поскольку оно позволяет избежать ненужной работы. Например, если это запрос статического файла, такого как файл CSS, JavaScript, изображение и т. д., middleware-компонент для статических файлов может обработать и обслужить этот запрос, а затем замкнуть остальную часть конвейера.

Давайте создадим ASP.NET Core веб-приложение и рассмотрим конфигурацию middleware по умолчанию в методе Configure класса Startup.

Фреймворк ASP.NET Core предоставляет встроенные middleware-компоненты, которые мы можем легко использовать, добавляя в метод Configure. Ознакомьтесь с документацией Microsoft для получения более подробной информации.

Упорядочение Middleware

Middleware-компоненты выполняются в том порядке, в котором они добавляются в конвейер, по этому следует проявлять осторожность и добавлять middleware в правильном порядке, иначе приложение может работать не так, как вы ожидаете. Порядок расположения middleware важен для безопасности, производительности и функциональности.

Следующие middleware-компоненты предназначены для стандартных сценариев приложений и расположены в рекомендуемом порядке:

Методы Run, Use и Map

app.Run()

Этот метод добавляет middleware-компонент в виде Run[Middleware], который выполнится в конце конвейера. Как правило, он действует как замыкающее middleware и добавляется в конце конвейера запросов, поскольку не может вызывать следующий middleware-компонент.

app.Use()

Этот метод используется для конфигурирования нескольких middleware. В отличие от app.Run(), мы можем включить в него параметр next, который вызывает следующий делегат запроса в конвейере. Мы также можем замкнуть (завершить) конвейер, не вызывая параметр next.

Давайте рассмотрим следующий пример с app.Use() и app.Run() и проанализируем результат/ответ:

app.Map()

Этот метод расширения используются как условное обозначение для ветвления конвейера. Map разветвляет конвейер запросов на основе пути запроса. Если путь запроса начинается с указанного пути, ветвь выполняется.

Давайте рассмотрим следующий пример с app.Map() и проанализируем результат/ответ:

В следующей таблице показаны запросы и ответы от localhost с использованием приведенного выше кода.

Источник

URL Rewriting Middleware in ASP.NET Core

This document introduces URL rewriting with instructions on how to use URL Rewriting Middleware in ASP.NET Core apps.

URL rewriting is the act of modifying request URLs based on one or more predefined rules. URL rewriting creates an abstraction between resource locations and their addresses so that the locations and addresses aren’t tightly linked. URL rewriting is valuable in several scenarios to:

URL rewriting can reduce the performance of an app. Where feasible, limit the number and complexity of rules.

URL redirect and URL rewrite

The difference in wording between URL redirect and URL rewrite is subtle but has important implications for providing resources to clients. ASP.NET Core’s URL Rewriting Middleware is capable of meeting the need for both.

A URL redirect involves a client-side operation, where the client is instructed to access a resource at a different address than the client originally requested. This requires a round trip to the server. The redirect URL returned to the client appears in the browser’s address bar when the client makes a new request for the resource.

When redirecting requests to a different URL, indicate whether the redirect is permanent or temporary by specifying the status code with the response:

For more information on status codes, see RFC 2616: Status Code Definitions.

A URL rewrite is a server-side operation that provides a resource from a different resource address than the client requested. Rewriting a URL doesn’t require a round trip to the server. The rewritten URL isn’t returned to the client and doesn’t appear in the browser’s address bar.

Although the client might be able to retrieve the resource at the rewritten URL, the client isn’t informed that the resource exists at the rewritten URL when it makes its request and receives the response.

URL rewriting sample app

You can explore the features of the URL Rewriting Middleware with the sample app. The app applies redirect and rewrite rules and shows the redirected or rewritten URL for several scenarios.

When to use URL Rewriting Middleware

Use URL Rewriting Middleware when you’re unable to use the following approaches:

Also, use the middleware when the app is hosted on HTTP.sys server (formerly called WebListener).

The main reasons to use the server-based URL rewriting technologies in IIS, Apache, and Nginx are:

The middleware doesn’t support the full features of these modules.

Some of the features of the server modules don’t work with ASP.NET Core projects, such as the IsFile and IsDirectory constraints of the IIS Rewrite module. In these scenarios, use the middleware instead.

The performance of the middleware probably doesn’t match that of the modules.

Benchmarking is the only way to know for sure which approach degrades performance the most or if degraded performance is negligible.

Package

URL Rewriting Middleware is provided by the Microsoft.AspNetCore.Rewrite package, which is implicitly included in ASP.NET Core apps.

Extension and options

Establish URL rewrite and redirect rules by creating an instance of the RewriteOptions class with extension methods for each of your rewrite rules. Chain multiple rules in the order that you would like them processed. The RewriteOptions are passed into the URL Rewriting Middleware as it’s added to the request pipeline with UseRewriter:

Redirect non-www to www

Three options permit the app to redirect non- www requests to www :

URL redirect

A round trip is made to the server when a URL is redirected.

Be cautious when establishing redirect rules. Redirect rules are evaluated on every request to the app, including after a redirect. It’s easy to accidentally create a loop of infinite redirects.

Original Request: /redirect-rule/1234/5678

URL redirect to a secure endpoint

When redirecting to a secure endpoint without the requirement for additional redirect rules, we recommend using HTTPS Redirection Middleware. For more information, see the Enforce HTTPS topic.

Original Request using AddRedirectToHttps(301, 5001) : http://localhost:5000/secure

Original Request using AddRedirectToHttpsPermanent : http://localhost:5000/secure

URL rewrite

Use AddRewrite to create a rule for rewriting URLs. The first parameter contains the regex for matching on the incoming URL path. The second parameter is the replacement string. The third parameter, skipRemainingRules: , indicates to the middleware whether or not to skip additional rewrite rules if the current rule is applied.

Original Request: /rewrite-rule/1234/5678

The carat ( ^ ) at the beginning of the expression means that matching starts at the beginning of the URL path.

Path Match
/redirect-rule/1234/5678 Yes
/my-cool-redirect-rule/1234/5678 Yes
/anotherredirect-rule/1234/5678 Yes
Path Match
/rewrite-rule/1234/5678 Yes
/my-cool-rewrite-rule/1234/5678 No
/anotherrewrite-rule/1234/5678 No

Use skipRemainingRules: true whenever possible because matching rules is computationally expensive and increases app response time. For the fastest app response:

Apache mod_rewrite

Apply Apache mod_rewrite rules with AddApacheModRewrite. Make sure that the rules file is deployed with the app. For more information and examples of mod_rewrite rules, see Apache mod_rewrite.

A StreamReader is used to read the rules from the ApacheModRewrite.txt rules file:

Original Request: /apache-mod-rules-redirect/1234

The middleware supports the following Apache mod_rewrite server variables:

IIS URL Rewrite Module rules

To use the same rule set that applies to the IIS URL Rewrite Module, use AddIISUrlRewrite. Make sure that the rules file is deployed with the app. Don’t direct the middleware to use the app’s web.config file when running on Windows Server IIS. With IIS, these rules should be stored outside of the app’s web.config file in order to avoid conflicts with the IIS Rewrite module. For more information and examples of IIS URL Rewrite Module rules, see Using Url Rewrite Module 2.0 and URL Rewrite Module Configuration Reference.

A StreamReader is used to read the rules from the IISUrlRewrite.xml rules file:

Original Request: /iis-rules-rewrite/1234

If you have an active IIS Rewrite Module with server-level rules configured that would impact your app in undesirable ways, you can disable the IIS Rewrite Module for an app. For more information, see Disabling IIS modules.

Unsupported features

The middleware doesn’t support the following IIS URL Rewrite Module features:

Supported server variables

The middleware supports the following IIS URL Rewrite Module server variables:

You can also obtain an IFileProvider via a PhysicalFileProvider. This approach may provide greater flexibility for the location of your rewrite rules files. Make sure that your rewrite rules files are deployed to the server at the path you provide.

Method-based rule

Use Add to implement your own rule logic in a method. Add exposes the RewriteContext, which makes available the HttpContext for use in your method. The RewriteContext.Result determines how additional pipeline processing is handled. Set the value to one of the RuleResult fields described in the following table.

Rewrite context result Action
RuleResult.ContinueRules (default) Continue applying rules.
RuleResult.EndResponse Stop applying rules and send the response.
RuleResult.SkipRemainingRules Stop applying rules and send the context to the next middleware.

This approach can also rewrite requests. The sample app demonstrates rewriting the path for any text file request to serve the file.txt text file from the wwwroot folder. Static File Middleware serves the file based on the updated request path:

IRule-based rule

Use Add to use rule logic in a class that implements the IRule interface. IRule provides greater flexibility over using the method-based rule approach. Your implementation class may include a constructor that allows you can pass in parameters for the ApplyRule method.

Original Request: /image.png

Original Request: /image.jpg

Regex examples

Goal Regex String &
Match Example
Replacement String &
Output Example
Rewrite path into querystring ^path/(.*)/(.*)
/path/abc/123
path?var1=$1&var2=$2
/path?var1=abc&var2=123
Strip trailing slash (.*)/$
/path/
$1
/path
Enforce trailing slash (.*[^/])$
/path
$1/
/path/
Avoid rewriting specific requests ^(.*)(? or ^(. *\.axd$)(.*)$
Yes: /resource.htm
No: /resource.axd
rewritten/$1
/rewritten/resource.htm
/resource.axd
Rearrange URL segments path/(.*)/(.*)/(.*)
path/1/2/3
path/$3/$2/$1
path/3/2/1
Replace a URL segment ^(.*)/segment2/(.*)
/segment1/segment2/segment3
$1/replaced/$2
/segment1/replaced/segment3

This document introduces URL rewriting with instructions on how to use URL Rewriting Middleware in ASP.NET Core apps.

URL rewriting is the act of modifying request URLs based on one or more predefined rules. URL rewriting creates an abstraction between resource locations and their addresses so that the locations and addresses aren’t tightly linked. URL rewriting is valuable in several scenarios to:

URL rewriting can reduce the performance of an app. Where feasible, limit the number and complexity of rules.

URL redirect and URL rewrite

The difference in wording between URL redirect and URL rewrite is subtle but has important implications for providing resources to clients. ASP.NET Core’s URL Rewriting Middleware is capable of meeting the need for both.

A URL redirect involves a client-side operation, where the client is instructed to access a resource at a different address than the client originally requested. This requires a round trip to the server. The redirect URL returned to the client appears in the browser’s address bar when the client makes a new request for the resource.

When redirecting requests to a different URL, indicate whether the redirect is permanent or temporary by specifying the status code with the response:

For more information on status codes, see RFC 2616: Status Code Definitions.

A URL rewrite is a server-side operation that provides a resource from a different resource address than the client requested. Rewriting a URL doesn’t require a round trip to the server. The rewritten URL isn’t returned to the client and doesn’t appear in the browser’s address bar.

Although the client might be able to retrieve the resource at the rewritten URL, the client isn’t informed that the resource exists at the rewritten URL when it makes its request and receives the response.

URL rewriting sample app

You can explore the features of the URL Rewriting Middleware with the sample app. The app applies redirect and rewrite rules and shows the redirected or rewritten URL for several scenarios.

When to use URL Rewriting Middleware

Use URL Rewriting Middleware when you’re unable to use the following approaches:

Also, use the middleware when the app is hosted on HTTP.sys server (formerly called WebListener).

The main reasons to use the server-based URL rewriting technologies in IIS, Apache, and Nginx are:

The middleware doesn’t support the full features of these modules.

Some of the features of the server modules don’t work with ASP.NET Core projects, such as the IsFile and IsDirectory constraints of the IIS Rewrite module. In these scenarios, use the middleware instead.

The performance of the middleware probably doesn’t match that of the modules.

Benchmarking is the only way to know for sure which approach degrades performance the most or if degraded performance is negligible.

Package

To include the middleware in your project, add a package reference to the Microsoft.AspNetCore.App metapackage in the project file, which contains the Microsoft.AspNetCore.Rewrite package.

When not using the Microsoft.AspNetCore.App metapackage, add a project reference to the Microsoft.AspNetCore.Rewrite package.

Extension and options

Establish URL rewrite and redirect rules by creating an instance of the RewriteOptions class with extension methods for each of your rewrite rules. Chain multiple rules in the order that you would like them processed. The RewriteOptions are passed into the URL Rewriting Middleware as it’s added to the request pipeline with UseRewriter:

Redirect non-www to www

Three options permit the app to redirect non- www requests to www :

URL redirect

A round trip is made to the server when a URL is redirected.

Be cautious when establishing redirect rules. Redirect rules are evaluated on every request to the app, including after a redirect. It’s easy to accidentally create a loop of infinite redirects.

Original Request: /redirect-rule/1234/5678

URL redirect to a secure endpoint

When redirecting to a secure endpoint without the requirement for additional redirect rules, we recommend using HTTPS Redirection Middleware. For more information, see the Enforce HTTPS topic.

Original Request using AddRedirectToHttps(301, 5001) : http://localhost:5000/secure

Original Request using AddRedirectToHttpsPermanent : http://localhost:5000/secure

URL rewrite

Use AddRewrite to create a rule for rewriting URLs. The first parameter contains the regex for matching on the incoming URL path. The second parameter is the replacement string. The third parameter, skipRemainingRules: , indicates to the middleware whether or not to skip additional rewrite rules if the current rule is applied.

Original Request: /rewrite-rule/1234/5678

The carat ( ^ ) at the beginning of the expression means that matching starts at the beginning of the URL path.

Path Match
/redirect-rule/1234/5678 Yes
/my-cool-redirect-rule/1234/5678 Yes
/anotherredirect-rule/1234/5678 Yes
Path Match
/rewrite-rule/1234/5678 Yes
/my-cool-rewrite-rule/1234/5678 No
/anotherrewrite-rule/1234/5678 No

Use skipRemainingRules: true whenever possible because matching rules is computationally expensive and increases app response time. For the fastest app response:

Apache mod_rewrite

Apply Apache mod_rewrite rules with AddApacheModRewrite. Make sure that the rules file is deployed with the app. For more information and examples of mod_rewrite rules, see Apache mod_rewrite.

A StreamReader is used to read the rules from the ApacheModRewrite.txt rules file:

Original Request: /apache-mod-rules-redirect/1234

The middleware supports the following Apache mod_rewrite server variables:

IIS URL Rewrite Module rules

To use the same rule set that applies to the IIS URL Rewrite Module, use AddIISUrlRewrite. Make sure that the rules file is deployed with the app. Don’t direct the middleware to use the app’s web.config file when running on Windows Server IIS. With IIS, these rules should be stored outside of the app’s web.config file in order to avoid conflicts with the IIS Rewrite module. For more information and examples of IIS URL Rewrite Module rules, see Using Url Rewrite Module 2.0 and URL Rewrite Module Configuration Reference.

A StreamReader is used to read the rules from the IISUrlRewrite.xml rules file:

Original Request: /iis-rules-rewrite/1234

If you have an active IIS Rewrite Module with server-level rules configured that would impact your app in undesirable ways, you can disable the IIS Rewrite Module for an app. For more information, see Disabling IIS modules.

Unsupported features

The middleware released with ASP.NET Core 2.x doesn’t support the following IIS URL Rewrite Module features:

Supported server variables

The middleware supports the following IIS URL Rewrite Module server variables:

You can also obtain an IFileProvider via a PhysicalFileProvider. This approach may provide greater flexibility for the location of your rewrite rules files. Make sure that your rewrite rules files are deployed to the server at the path you provide.

Method-based rule

Use Add to implement your own rule logic in a method. Add exposes the RewriteContext, which makes available the HttpContext for use in your method. The RewriteContext.Result determines how additional pipeline processing is handled. Set the value to one of the RuleResult fields described in the following table.

Rewrite context result Action
RuleResult.ContinueRules (default) Continue applying rules.
RuleResult.EndResponse Stop applying rules and send the response.
RuleResult.SkipRemainingRules Stop applying rules and send the context to the next middleware.

This approach can also rewrite requests. The sample app demonstrates rewriting the path for any text file request to serve the file.txt text file from the wwwroot folder. Static File Middleware serves the file based on the updated request path:

IRule-based rule

Use Add to use rule logic in a class that implements the IRule interface. IRule provides greater flexibility over using the method-based rule approach. Your implementation class may include a constructor that allows you can pass in parameters for the ApplyRule method.

Источник

Читайте также:  мартини и деласи чем отличаются
Образовательный портал