在我的WebAPI项目中,我遇到了一些重定向的问题。这是因为Uri.ToString()方法的行为是“防御性的”,换句话说,一旦调用了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;
}
}
}现在,我不能通过从Uri属性构造自己的链接来修改此行为,因为我无法控制它。在我的控制器中,为了重定向调用,我确实以以下方式响应get消息:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Found);
response.Headers.Location = // my Uri object在特定的时间点之前,这种方法工作得很好。如果我的重定向Uri包含一个包含编码链接的查询,它将返回错误的结果。(这可能是因为通过在该属性上调用ToString来读取Headers.Location。
有没有人知道如何克服这个问题?
谢谢
发布于 2019-12-02 23:12:43
Uri.ToString()可以解码URL编码的序列。(就像%20=>是一个空格)。不同版本的.net框架之间的行为也会有所不同。
简而言之,不使用Uri.ToString(),而使用Uri.AbsoluteUri或Uri.OriginalString。
有关深入调查https://dhvik.blogspot.com/2019/12/uritostring-automatically-decodes-url.html的信息,请参阅以下文章
https://stackoverflow.com/questions/21630514
复制相似问题