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

ⅰ亾dé卋堺 提交于 2019-12-02 21:41:48
rboarman

Try:

var url = filterContext.HttpContext.Request.Url;

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

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.

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}";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!