Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place HttpContext.Current.RewritePath in ASP.NET 5?

I do development in asp.net. Recently I found out that in asp.net 5 there is no Global.asax file.

One of the thing to put in Global.asax file is URL rewriting.

With Global.asax file is gone. Where I can place URL rewriting code. I mean I do something like this in ASP.NET 4.0

 HttpContext.Current.RewritePath(...);

I do not want to use URL rewriting modules. I just want to do it using HttpContext.Current.RewritePath method.

My question is where I can put the above code in ASP.NET 5?

like image 701
user786 Avatar asked Dec 10 '25 09:12

user786


2 Answers

Create and add a new middleware at the beginning of Configure method in your Startup (you want it to execute before any other middlewares). Example here

Implement invoke method as follows to do a url rewrite

public Task Invoke(HttpContext context)
{
    // modify url
    context.Request.Path = new PathString(context.Request.Path.Value + 'whatever');
    // continue
    return _next(context);
}

I came across this when I was analyzing aspnet/StaticFiles repo on Github.

like image 84
mbudnik Avatar answered Dec 11 '25 21:12

mbudnik


As an alternative to explicitly creating a middleware class, IApplicationBuilder.Use can be used too:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //...built-in initialization...

    app.Use(requestDelegate =>
    {
        return new RequestDelegate(context =>
        {
            // modify url (from mbudnik's answer)
            context.Request.Path = new PathString(context.Request.Path.Value + 'whatever');

            // continue with the pipeline
            return requestDelegate(context);
        });
    });
}

In this case the middlewares are specified directly as instances of Func<RequestDelegate, RequestDelegate>, instead of custom classes.

like image 36
Konamiman Avatar answered Dec 11 '25 22:12

Konamiman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!