[英]Dynamic Url rewrite in ASP.NET CORE
我正在嘗試重寫 URL,並檢測 URL 的一部分是否存在,然后處理該字符串以最終創建最終 URL。
從本文中,我找到了一種使用正則表達式替換 URL 段的方法。
我的情況如下:給定 URL
www.whatever.com/segment1/segment2?parameter=value
我需要檢測 URL 中是否存在文本“ parameter = ”,然后處理該值並得到如下內容:
www.whatever.com/segment1/segment2?parameter=valueConverted
首先,我嘗試做類似的事情:
var options = new RewriteOptions()
.AddRedirect("segment1/segment2/(.*)", "segment2/$1");
效果很好,但后來我被要求處理參數的值。 但我還沒有發現類似的東西:
var options = new RewriteOptions()
.AddRewrite(@"^param=$", "param=" MethodCall(how to send value here?) );
任何指導?
我發現了一些像這樣的有趣文章,它們幫助我完成了這個……看看我的最終代碼:
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;
}
}
更新:您必須小心重定向循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.