Paule Paul
Paule Paul

Reputation: 387

A HttpRequest Redirect Exception in UWP Project

The code goes below

public static async Task<string> getForwardUrl(string url)
{
    try
    {
        HttpClient client = new HttpClient();
        HttpRequestMessage forwardRequest = new HttpRequestMessage();

        forwardRequest.RequestUri = new Uri(url);
        HttpResponseMessage Message = await client.SendAsync(forwardRequest);
        return Message.RequestMessage.RequestUri.OriginalString;
    }
    catch (Exception ex)
    {
        WriteLine(ex.Message);
    }
    //...
}

When I run this in a uwp project, exception occurs. The message of this exception shows that the redirection request would change the safe connection to an unsafe one(After that , I checked the URL of the login page , It's https ,but the page after I logged in is http).

I find a similar question, he recommends using Windows.Web.Http instead of System.Net.Http but I get the same error message.

Thanks for your reply

EDIT: The URL is: https://tinyurl.com /57muy (remove the space) or short a http url with tinyurl.com! The problem only occurs with a shortet http side! Error: An error occurred while sending the request. Innermessage: Error message not found for this error

Upvotes: 0

Views: 376

Answers (1)

Jay Zuo
Jay Zuo

Reputation: 15758

According to your description, I'd suppose you are developing a UWP app. And as you've mentioned, we got the exception here because the redirection request would change the safe connection to an unsafe one. To solve this problem, we can turn off auto-redirect and do the redirection by ourselves.

For example:

public static async Task<string> getForwardUrl(string url)
{
    var handler = new System.Net.Http.HttpClientHandler();
    handler.AllowAutoRedirect = false;

    var client = new System.Net.Http.HttpClient(handler);

    var response = await client.GetAsync(url);

    if (response.StatusCode == System.Net.HttpStatusCode.Redirect || response.StatusCode == System.Net.HttpStatusCode.Moved)
    {
        return response.Headers.Location.AbsoluteUri;
    }

    return url;
} 

Upvotes: 1

Related Questions