C# 在具有 .aspx 扩展名的 mvc 应用程序中获取 Current.Request.Url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17101891/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:35:41  来源:igfitidea点击:

Get Current.Request.Url in mvc application having a .aspx extension

c#asp.net-mvc

提问by Manish Gautam

I have a ASP.NET MVC 3 application in which I have to map a request with .aspx extension to another route. what i am trying to do is to get the current request url in application start. but the problem is it runs fine with all urls without .aspx extension but in a url for ex (http://example.com/Products/5/16/Eettafels.aspx) it shows only http://example.com/

我有一个 ASP.NET MVC 3 应用程序,我必须在其中将带有 .aspx 扩展名的请求映射到另一个路由。我想要做的是在应用程序启动时获取当前请求 url。但问题是它在所有没有 .aspx 扩展名的 url 上运行良好,但在 ex ( http://example.com/Products/5/16/Eettafels.aspx)的 url 中它只显示http://example.com/

however with http://example.com/Products/5/16/Eettafelsit shows the correct path ..

但是使用http://example.com/Products/5/16/Eettafels它显示了正确的路径..

All the code is a simple line:

所有代码都是简单的一行:

string currentUrl = HttpContext.Current.Request.Url.ToString().ToLower();

Can any one have any idea what i am doing wrong

任何人都知道我做错了什么吗

回答by Iftikhar Ali Ansari

though it is a very old post.

虽然这是一个很老的帖子。

I am just pasting the code Ha Doan linked to so that it will be easier to anyone landing on this question.

我只是粘贴 Ha Doan 链接的代码,以便任何人都能更轻松地解决这个问题。

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

Check this SO for discussion on this

检查此 SO 以对此进行讨论

回答by Tiramonium

Nowadays you can override a Controller method that executes before any Action is called. What I'd then suggest is you keep the current Url like @Ifitkhar suggested in a ViewBag, or TempData, in case you intend on redirecting, then using it later in the Action you want to return afterwards.

如今,您可以覆盖在调用任何 Action 之前执行的 Controller 方法。然后我建议您保留当前的 ​​Url,如在 ViewBag 或 TempData 中建议的 @Ifitkhar,以防您打算重定向,然后在稍后要返回的操作中使用它。

public class ProductsController
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext){
        TempData["previousUrl"] = HttpContext.Current.Request.Url.AbsoluteUri;
        base.OnActionExecuting(filterContext);
    }
}