检测URL重定向+ ASP.NET核心

时间:2017-12-14 02:49:44

标签: c# httpwebrequest url-redirection asp.net-core-1.1

我正在尝试将webform网址重定向到.net核心。 假设用户在URL中输入了 www.test.com/index.aspx ,它将重定向到 www.test.com/home/index

所以在HomeController,IActionResult Index方法中,如何检测到它是从index.aspx重定向到home / index?

我的研究表明它会像下面这样,但它们与.net核心不兼容

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

非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

您的代码与.Net Core 1.1不兼容,但与.Net Core 2.0兼容。因此,如果可能,只需更改目标框架。

您还应该稍微调整一下代码。如果重定向发生,.Net Core HttpWebRequest.GetResponse()方法将抛出WebException。所以你应该试着抓住它并分析WebException.Response

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

但我建议使用HttpClient作为替代方案。它将允许您在没有异常处理的情况下完成工作:

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方法适用于.Net Core 1.1和2.0版本。

<强>更新

IsRedirected中没有与HttpResponseMessage属性相似的内容,但您可以使用简单的扩展方法:

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();