简体   繁体   English

如何在没有ID或查询的情况下获取绝对路径?

[英]How to Get the Absolutepath Without the Id or Query?

Let's say my url is " https://www.mywebsite.com/app/company/employees/5 " or " https://www.mywebsite.com/company/employees?id=5&name=jack " 假设我的网址是“ https://www.mywebsite.com/app/company/employees/5 ”或“ https://www.mywebsite.com/company/employees?id=5&name=jack

I'm looking for a way to get the "base" path, or whatever it's called. 我正在寻找一种获取“基本”路径或任何所谓路径的方法。 Like the "base" path would be "/app/company/employees" for both, without the "/5" part or "?id=5&name=jack" part. 就像“基本”路径都将是“ / app / company / employees”一样,而没有“ / 5”部分或“?id = 5&name = jack”部分。

I was using string.Join("/", request.ApplicationPath, request.RequestContext.RouteData.Values["controller"], request.RequestContext.RouteData.Values["action"]) to get it (request is HttpRequestBase), but it doesn't work the way I want since it includes the Index action too. 我正在使用string.Join("/", request.ApplicationPath, request.RequestContext.RouteData.Values["controller"], request.RequestContext.RouteData.Values["action"])来获取它(请求是HttpRequestBase),但它也不符合我想要的方式,因为它也包含Index动作。 Like if the Url is " https://www.mywebsite.com/app/company " I want "/app/company/" not "/app/company/Index". 就像Url是“ https://www.mywebsite.com/app/company ”一样,我希望“ / app / company /”而不是“ / app / company / Index”。 I can always check if the action is Index or not but it feels like kind of a "code smell" to me. 我总是可以检查该动作是否为Index,但对我来说感觉像是一种“代码异味”。

Is it even a code smell? 甚至有代码味吗? Is there any proper way to accomplish this? 有什么适当的方法可以做到这一点吗?

The Uri Class offers many properties https://docs.microsoft.com/en-us/dotnet/api/system.uri?view=netframework-4.7.2 Uri类提供了许多属性https://docs.microsoft.com/zh-cn/dotnet/api/system.uri?view=netframework-4.7.2

Try this 尝试这个

string val = HttpContext.Current.Request.Url.AbsolutePath;

or in your case if your request variable is an HttpRequest object, try: 或者如果您的请求变量是HttpRequest对象,请尝试:

string val = request.Url.AbsolutePath;

使用HttpContext.Current.Request.Url.AbsolutePath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM