首页 > 解决方案 > Regex.Replace 或 String.Replace 不适用于 Linux 环境中的主机 URL

问题描述

我的安装
开发机器:

分期机:

我的问题
我有一个简单但奇怪的问题。在下面的代码块中,我生成了一个电子邮件确认链接。现在,我想用另一个替换生成的 URL 的域。

// class fields
        private readonly string _WebServerRelativeUrl = "https://www.specific-domain.com/account/";
        private readonly string _BingoServerRelativeUrl = "https://www.specific-domain.eu/api/v1/identity/";
        private readonly string _BingoLocalServerRelativeUrl = "https://localhost:44375/api/v1/identity/";


// code excerpt from confirm email method
var passwordResetLink = _urlHelper.Action("ResetPassword", "identity",
                new { email = appUser.Email, token, lang }, _httpRequest.HttpContext.Request.Scheme);

            var url = Regex.Replace(passwordResetLink, _BingoServerRelativeUrl, _WebServerRelativeUrl, RegexOptions.IgnoreCase);
            if (_environment.IsDevelopment())
            {
                url = Regex.Replace(passwordResetLink, _BingoLocalServerRelativeUrl, _WebServerRelativeUrl, RegexOptions.IgnoreCase);
            }

在本地主机上,一切正常。服务器生成如下 URL:

https://localhost:44375/api/v1/identity/confirmemail?userId=abcd&token=abcd

然后将 https://localhost:44375/api/v1/identity 成功替换为https://www.specific-domain.com/account/

但是,在生产环境中,该应用程序在 Ubuntu 18.04 上运行,位于具有特定域的 Nginx 后面。现在,当应用程序位于 Linux VM 上的生产环境中时,此字符串替换不起作用。

我还尝试了 String.Replace() 而不是正则表达式,结果相同。可能是什么问题?

标签: c#linuxasp.net-core

解决方案


调试这个问题需要相当多的时间。通过使用Flurl 库构建最初所需的 URL,找到了一个更简单的解决方案。该解决方案需要更少的代码。

var url = WebServerRelativeUrl
    .AppendPathSegment(ResetPassPath)
    .SetQueryParams(new
    {
         email = appUser.Email, token = token, lang = lang
    });

PS 我更喜欢这个而不是UriBuilder,因为它提供了流畅的界面。


推荐阅读