Uri ToString() 方法解码 Uri 查询



在我的WebAPI项目中,我在重定向方面遇到了一些问题。这是因为 Uri.ToString() 方法以"防御"方式运行,换句话说,一旦调用 mentione 方法,他就会解码查询字符串的安全部分。

请考虑以下失败的单元测试:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UriTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            // Arrange
            const string expectedUrlRaw = 
                "http://localhost/abc?proxy=http%3A%2F%2Ftarget.nl%3Fparam1%3Dvalue1%26param2%3Dvalue2";
            const string expectedUrlInHttpsRaw =
                "https://localhost/abc?proxy=http%3A%2F%2Ftarget.nl%3Fparam1%3Dvalue1%26param2%3Dvalue2";
            Uri expectedUri = new Uri(expectedUrlRaw);
            Uri expectedUriInHttps = new Uri(expectedUrlInHttpsRaw);
            // Act
            string returnsUriInHttpsRaw = expectedUri.ToHttps().ToString();
            // Assert
            Assert.AreEqual(expectedUrlInHttpsRaw, returnsUriInHttpsRaw);
        }
    }
    public static class StringExtensions
    {
        public static Uri ToHttps(this Uri uri)
        {
            UriBuilder uriBuilder = new UriBuilder(uri);
            uriBuilder.Scheme = Uri.UriSchemeHttps;
            uriBuilder.Port = 443;
            return uriBuilder.Uri;
        }
    }
}

现在,我无法通过从 Uri 属性构造自己的链接来修改此行为,因为我无法控制它。在我的控制器中,我确实以以下方式响应获取消息以重定向呼叫:

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Found);
            response.Headers.Location = // my Uri object

这在某一点之前工作正常。如果我的重定向 Uri 包含包含编码链接的查询,它将返回错误的结果。(这可能是因为 Headers.Location 是通过在该属性上调用 ToString 来读取的。

有没有人知道如何克服这个问题?

谢谢

Uri.ToString() 确实解码 URL 编码序列。(如 %20=>空格)。该行为也会在不同版本的 .net 框架之间发生变化。

简而言之,不要使用 Uri.ToString(),请使用Uri.AbsoluteUri 或 Uri.OriginalString

有关深入调查,请参阅以下文章https://dhvik.blogspot.com/2019/12/uritostring-automatically-decodes-url.html

最新更新