Uri ToString()方法解码Uri查询

Mai*_*iOM 5 c# uri httpresponse asp.net-web-api

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

考虑这个失败的单元测试:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我无法通过从Uri属性构建自己的链接来修改此行为,因为我无法控制它.在我的控制器中,我确实以下面的方式响应get消息以重定向调用:

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Found);
            response.Headers.Location = // my Uri object
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Dan*_*Dan 1

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

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

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