[英]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.我正在尝试重写 URL,并检测 URL 的一部分是否存在,然后处理该字符串以最终创建最终 URL。
From this article , I found so far a way to replace segments of the URL using a regex.从本文中,我找到了一种使用正则表达式替换 URL 段的方法。
My case is the following: given the URL我的情况如下:给定 URL
www.whatever.com/segment1/segment2?parameter=value
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:我需要检测 URL 中是否存在文本“ parameter = ”,然后处理该值并得到如下内容:
www.whatever.com/segment1/segment2?parameter=valueConverted
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.更新:您必须小心重定向循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.