【问题标题】:Detect URL redirection + ASP.NET Core检测 URL 重定向 + ASP.NET Core
【发布时间】:2017-12-14 02:49:44
【问题描述】:

我正在尝试将网络表单网址重定向到 .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");
    }

感谢您的帮助。

【问题讨论】:

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


    【解决方案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 版本。

    更新

    HttpResponseMessage 中没有类似于IsRedirected 属性的东西,但您可以使用简单的扩展方法:

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

    【讨论】:

    • 感谢您的回复,我正在尝试使用它,但是有没有检测到重定向的布尔值?例如,IsRedirected = true
    猜你喜欢
    • 2017-09-22
    • 2018-07-06
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    相关资源
    最近更新 更多