【问题标题】:AbsoluteUri need to return correct pathAbsoluteUri 需要返回正确的路径
【发布时间】:2017-12-04 02:26:13
【问题描述】:

在我的 MVC 视图中使用下面的方法,我得到了类似“localhost:54871/Home/Index”的 URL,但我不希望最后出现“索引”。它应该只是“localhost:54871/Home”。我应该如何实现这个?

@(Request.Url.AbsoluteUri)

感谢您的帮助!

【问题讨论】:

  • 你可以做他的路线,刚刚给了 Redirect.toRoute("yourroute") 希望对你有帮助
  • Index 是您的操作方法名称,您是否只想显示 Controller 名称?

标签: c# asp.net-mvc


【解决方案1】:

使用Request.Url.AbsoluteUri时,url会根据用户的当前页面而变化。

如果用户访问http://localhost:0000/Home/,那么AbsoluteUri就是http://localhost:0000/Home/

如果用户访问http://localhost:0000/Home/Index,那么AbsoluteUri就是http://localhost:0000/Home/Index

MVC 中,url 的生成是基于RouteConfig.cs 文件中定义的路由定义。

你可以只为控制器名称定义路由,检查thisthis

还有另一种解决方案如下:

@{
Uri uriAddress = new Uri(Request.Url.AbsoluteUri);

string urlLeftPart = uriAddress.GetLeftPart(UriPartial.Authority);

string controllerName = HttpContext.Current.Request.RequestContext.RouteData.
Values["controller"].ToString();

string finalURL = urlLeftPart + "/" + controllerName;
}

<a href="@finalURL">Url Without Action Name</a>

参考文献

1.

2.

【讨论】:

    【解决方案2】:

    你可以试试下面这个。

    例如,如果带有参数的url如下所示

    http://localhost:61221/Websitetest/Default1.aspx?QueryString1=1&QueryString2=2
    

    然后使用下面的代码可以得到结果

    HttpContext.Current.Request.Url.Host
    HttpContext.Current.Request.Url.Authority
    HttpContext.Current.Request.Url.Port
    HttpContext.Current.Request.Url.AbsolutePath
    HttpContext.Current.Request.ApplicationPath
    HttpContext.Current.Request.Url.AbsoluteUri
    HttpContext.Current.Request.Url.PathAndQuery
    

    将提供如下输出

    输出

    localhost
    localhost:61221
    61221
    /Websitetest/Default1.aspx
    /Websitetest
    http://localhost:61221/Websitetest/Default1.aspx?QueryString1=1&QueryString1=2
    /Websitetest/Default1.aspx?QueryString1=1&QueryString2=2
    

    【讨论】:

      猜你喜欢
      • 2015-07-06
      • 1970-01-01
      • 2012-03-29
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多