【发布时间】:2014-02-07 14:41:52
【问题描述】:
在我的 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;
}
}
}
现在,我无法通过从 Uri 属性构建自己的链接来修改此行为,因为我无法控制它。 在我的控制器中,我确实以以下方式响应获取消息以重定向呼叫:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Found);
response.Headers.Location = // my Uri object
这工作正常,直到某一点。如果我的重定向 Uri 包含一个包含编码链接的查询,它将返回错误的结果。 (这可能是因为 Headers.Location 是通过在该属性上调用 ToString 来读取的。
有人知道如何解决这个问题吗?
谢谢
【问题讨论】:
-
您找到解决方案了吗?我遇到了同样的问题...
-
不,我没有。对不起。
-
我发现了一篇关于此的博客文章。很多话归结为根本不使用
ToString方法。太糟糕了,一些 .NET 类在内部使用它(例如HttpClient)...
标签: c# uri httpresponse asp.net-web-api