Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 替换请求的URL节_C#_Asp.net_Regex - Fatal编程技术网

C# 替换请求的URL节

C# 替换请求的URL节,c#,asp.net,regex,C#,Asp.net,Regex,我有一个在URL中包含语言说明符的网站(例如) 使用正则表达式,我可以解析出URL的语言: Match match = Regex.Match(HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath, "^~/(?<language>[^/]+)/"); 我现在正在寻找一种比野蛮的字符串操作更简单的方法,如果需要的话,用一种新的语言来替换这种语言 因此,上面的URL将更改为 我最初的想法是一个简单的搜索/替换,

我有一个在URL中包含语言说明符的网站(例如)

使用正则表达式,我可以解析出URL的语言:

Match match = Regex.Match(HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath, "^~/(?<language>[^/]+)/");
我现在正在寻找一种比野蛮的字符串操作更简单的方法,如果需要的话,用一种新的语言来替换这种语言

因此,上面的URL将更改为

我最初的想法是一个简单的搜索/替换,但是这不起作用,因为页面名称或其他URL片段中可能包含语言名称。我只关心根URL之后的第一个片段


在更改URL之后,我将重定向用户并完成它

您可以创建一个Uri对象,然后使用PathAndQuery提取路径拆分“/”并替换第一个实例,然后再次构造Uri,或者您可以使用:

string requestUrl=“~/English/rest/of/url.aspx”;
字符串targetLanguage=“德语”;
Match Match=Regex.Match(requestUrl,“^~/(?[^/]+)/”;
if(match.Groups[“language”].Value!=targetLanguage)
重定向(Regex.Replace(requestUrl,“^~/[^/]+/”,string.Format(“~/{0}/”,targetLanguage));

Doh,就在我面前。工作完美。谢谢
match.Groups["language"].Value
string requestUrl = "~/English/rest/of/url.aspx";
string targetLanguage = "German";
Match match = Regex.Match(requestUrl, "^~/(?<language>[^/]+)/");
if (match.Groups["language"].Value != targetLanguage)
    Response.Redirect(Regex.Replace(requestUrl, "^~/[^/]+/", string.Format("~/{0}/", targetLanguage)));