How do I get the current Url from within a FilterAttribute?

后端 未结 4 2067
星月不相逢
星月不相逢 2021-02-03 18:17

I am writing an Authorize filter attribute adn I\'m having trouble figuring out how to get the current url as a string so I can pass it as a parameter to the LogOn action. The g

相关标签:
4条回答
  • 2021-02-03 18:35

    In my specific case I was after the UrlReferrer URL.

    filterContext.HttpContext.Request.UrlReferrer
    

    This one let me redirect the user back to the page he was before trying to access an action he doesn't have permission to access.

    0 讨论(0)
  • 2021-02-03 18:37

    Try:

    var url = filterContext.HttpContext.Request.Url;
    
    0 讨论(0)
  • 2021-02-03 18:47

    To get the complete URL you can try as suggested by the @rboarman but usually the RedirectUrl will be the relative url and for that you have to try the the RawUrl property of the Request object.

    filterContext.HttpContext.Request.Url  ===> http://somesite.com/admin/manage
    
    filterContext.HttpContext.Request.RawUrl ====> /admin/manage
    

    EDITED: Fixed the second example

    0 讨论(0)
  • 2021-02-03 18:50

    This is the highest ranked result on Google so in Asp.net Core 2.0 this is how I'm doing it:

    context.HttpContext.Request.Url();
    

    using this extension method:

    /// <summary>
    /// Returns the absolute url.
    /// </summary>
    public static string Url(this HttpRequest request)
    {
        return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
    }
    
    0 讨论(0)
提交回复
热议问题