asp.net-mvc 如何从 FilterAttribute 中获取当前 Url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10761551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the current Url from within a FilterAttribute?
提问by quakkels
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.
我正在编写一个授权过滤器属性,我无法弄清楚如何将当前 url 作为字符串获取,以便我可以将它作为参数传递给登录操作。目标是如果用户成功登录,他们将被重定向到他们最初尝试访问的页面。
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?
如何从当前请求中获取完整的字符串 Url?
回答by rboarman
Try:
尝试:
var url = filterContext.HttpContext.Request.Url;
回答by VJAI
To get the complete URLyou can try as suggested by the @rboarmanbut usually the RedirectUrlwill be the relative urland for that you have to try the the RawUrlproperty of the Requestobject.
要获得完整的内容,URL您可以按照 的建议进行尝试,@rboarman但通常RedirectUrl将是相对 url,为此您必须尝试对象的RawUrl属性Request。
filterContext.HttpContext.Request.Url ===> http://somesite.com/admin/manage
filterContext.HttpContext.Request.RawUrl ====> /admin/manage
EDITED: Fixed the second example
编辑:修正了第二个例子
回答by Leniel Maccaferri
In my specific case I was after the UrlReferrerURL.
在我的特定情况下,我是在UrlReferrerURL 之后。
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.
这让我在尝试访问他无权访问的操作之前将用户重定向回他所在的页面。
回答by jmdon
This is the highest ranked result on Google so in Asp.net Core 2.0 this is how I'm doing it:
这是 Google 上排名最高的结果,因此在 Asp.net Core 2.0 中,我是这样做的:
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}";
}

