How to use OWIN middleware to rewrite a version of a URL to request a static file?

eg. I have a file located on the /Content/static/home.html server. I want to be able to query /Content/v/1.0.0.0/static/home.html (for version control) and rewrite the URL so that it accesses the file with the correct URL using the OWIN middleware.

I am currently using the URL rewrite module (IIS extension), but I want to do this work in the OWIN pipeline.

+6
source share
3 answers

I found a solution using the Microsoft.Owin.StaticFiles nuget package:

First, make sure this is in your web configuration, so static file requests are sent to OWIN:

 <system.webServer> ... <modules runAllManagedModulesForAllRequests="true"></modules> ... </system.webServer> 

Then in your download setup method add this code:

 // app is your IAppBuilder app.Use(typeof(MiddlewareUrlRewriter)); app.UseStaticFiles(); app.UseStageMarker(PipelineStage.MapHandler); 

And here is MiddlewareUrlRewriter:

 public class MiddlewareUrlRewriter : OwinMiddleware { private static readonly PathString ContentVersioningUrlSegments = PathString.FromUriComponent("/content/v"); public MiddlewareUrlRewriter(OwinMiddleware next) : base(next) { } public override async Task Invoke(IOwinContext context) { PathString remainingPath; if (context.Request.Path.StartsWithSegments(ContentVersioningUrlSegments, out remainingPath) && remainingPath.HasValue && remainingPath.Value.Length > 1) { context.Request.Path = new PathString("/Content" + remainingPath.Value.Substring(remainingPath.Value.IndexOf('/', 1))); } await Next.Invoke(context); } } 

As an example, this allows the GET request /Content/v/1.0.0.0/static/home.html to get the file in /Content/static/home.html .

UPDATE: Added app.UseStageMarker(PipelineStage.MapHandler); after other app.Use methods, as required to do the job. http://katanaproject.codeplex.com/wikipage?title=Static%20Files%20on%20IIS

+9
source

Theoretically, you can do this using UseStaticFiles with options instead of a separate UrlRewriter middleware:

 string root = AppDomain.CurrentDomain.BaseDirectory; var staticFilesOptions = new StaticFileOptions(); staticFilesOptions.RequestPath = new PathString("/foo"); staticFilesOptions.FileSystem = new PhysicalFileSystem(Path.Combine(root, "web")); app.UseStaticFiles(staticFilesOptions); 

But see this question as it is currently not working.

+2
source

Now here is the Owin.UrlRewrite project: https://github.com/gertjvr/owin.urlrewrite

It is syntactically based on Apache mod_rewrite.

0
source

Source: https://habr.com/ru/post/971888/


All Articles