Search code examples
c#httpwebrequesthttp-redirectasp.net-core-1.1

Detect URL redirection + ASP.NET Core


I'm trying to redirect webform urls to .net core. Lets say user entered www.test.com/index.aspx in URL, it will redirect to www.test.com/home/index

So in the HomeController, IActionResult Index method, how can I detect that it was redirected from index.aspx to home/index?

My research shows that it would be something like below, but they are not compatible with .net core

var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "HEAD";
    request.AllowAutoRedirect = false;

    string location;
    using (var response = request.GetResponse() as HttpWebResponse)
    {
        location = response.GetResponseHeader("Location");
    }

Help is appreciated.


Solution

  • Your code is not compatible with .Net Core 1.1, however is compatible with .Net Core 2.0. So if possible just change target framework.

    You should also adjust your code slightly. In .Net Core HttpWebRequest.GetResponse() method will throw WebException if redirect happens. So you should try-catch it and analyze WebException.Response:

    try
    {
        using (request.GetResponse() as HttpWebResponse)
        {
        }
    }
    catch (WebException e)
    {
        var location = e.Response.Headers["Location"];
    }
    

    However I suggest using HttpClient as alternative. It will allow you to do the job without exception handling:

    using (HttpClientHandler handler = new HttpClientHandler())
    {
        handler.AllowAutoRedirect = false;
        using (HttpClient httpClient = new HttpClient(handler))
        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, uri))
        using (var response = await httpClient.SendAsync(request))
        {
            var location = response.Headers.Location;
        }
    }
    

    HttpClient approach works both for .Net Core 1.1 and 2.0 versions.

    UPDATE

    There is no something similar to IsRedirected property in HttpResponseMessage but you could use simple extension method for it:

    public static class HttpResponseMessageExtensions
    {
        public static bool IsRedirected(this HttpResponseMessage response)
        {
            var code = response.StatusCode;
            return code == HttpStatusCode.MovedPermanently || code == HttpStatusCode.Found;
        }
    }
    
    bool redirected = response.WasRedirected();