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

4

53

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 goal is that if a user successfully logs on, they will be redirected to the page they were originally trying to access.

public override void OnAuthorization(AuthorizeContext filterContext)
{
    base.OnAuthorization(filterContext);

    ... my auth code ...
    bool isAuth ;
    ... my auth code ...

    if(!isAuth)
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary { 
                { "Area", "" }, 
                { "Controller", "Account" }, 
                { "Action", "LogOn" },
                { "RedirectUrl", "/Url/String/For/Currnt/Request" } // how do I get this?
            }
        );
    }
}

How do I get the full string Url from the current request?

Coney answered 25/5, 2012 at 21:25 Comment(0)
S
86

Try:

var url = filterContext.HttpContext.Request.Url;
Sutphin answered 25/5, 2012 at 21:30 Comment(1)
You could also use RawUrl (filterContext.HttpContext.Request.RawUrl) to get url without domainJute
M
19

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

Moidore answered 26/5, 2012 at 13:0 Comment(3)
Did you mean for "RawUrl" to be used in your 2nd example?Grimonia
-1 Observing the value of Url does not magically make it absolute then relative.Orometer
@JoshNoe Yes I meant the RawUrl in the second example. I'm little away from SO nowadays and I missed to see your comment.Moidore
G
7

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.

Ginsberg answered 4/5, 2013 at 8:53 Comment(0)
D
5

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}";
}
Debbradebby answered 4/5, 2018 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.