简体   繁体   中英

Dynamic Url rewrite in ASP.NET CORE

I'm trying to rewrite a URL, and detect if a portion of the URL exists, then process that string to finally create a final URL.

From this article , I found so far a way to replace segments of the URL using a regex.

My case is the following: given the URL

www.whatever.com/segment1/segment2?parameter=value

I need to detect if the text " parameter= " exist in the URL and then process the value and get something like:

www.whatever.com/segment1/segment2?parameter=valueConverted

First, I tried doing something like:

var options = new RewriteOptions() 
  .AddRedirect("segment1/segment2/(.*)", "segment2/$1");

which worked fine but I was later asked to process the value of the parameter. But I have not found something similar to this yet:

var options = new RewriteOptions()  
  .AddRewrite(@"^param=$", "param=" MethodCall(how to send value here?) );

Any guidance?

I found some interesting articles like this that helped me accomplish this... take a look at my final code:

 public void Configure(IApplicationBuilder app ...
 {
        var options = new RewriteOptions()              
            .Add(new MyCustomRules());
            
            
}

...

 public class MyCustomRules : Microsoft.AspNetCore.Rewrite.IRule
    {
    private int StatusCode { get; } = (int)System.Net.HttpStatusCode.MovedPermanently;

    private const string PARAMETER = "parameter=";

    public void ApplyRule(RewriteContext context)
    {
        var request = context.HttpContext.Request;
        var host = request.Host;
        var url = request.Path.Value;
        var queryString = request.QueryString.Value;
  

        if (queryString.Contains(PARAMETER, StringComparison.OrdinalIgnoreCase))
        {
            var host = request.Host;
            var originalText = queryString.Split(PARAMETER)[1]; 

            var convertedText = processText.Method(originalText);

            var newUrl = request.Scheme +  host.Value + request.Path + "?" + PARAMETER + convertedText;
            var response = context.HttpContext.Response;
            response.StatusCode = StatusCode;
            response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location] = newUrl;
            context.Result = RuleResult.EndResponse;
            return;
        }

        context.Result = RuleResult.ContinueRules;
        return;
    }
}   

UPDATE: you have to be careful about redirect Looping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM