Uri ToString () Method Decoding Uri Query

In my WebAPI project, I have some redirection problems. This is because the Uri.ToString () method behaves in a “defensive” way, in word-words, as soon as the mention method is called, it decodes the safe parts of the query string.

Consider this unit test failure:

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;
        }
    }
}

Now I can’t change this behavior by building my own link from the Uri properties, since I do not control it. In my controller, I respond as follows to receiving a message in order to redirect the call:

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

. Uri , , . (, , , Headers.Location ToString .

- , ?

+3

All Articles