如何知道 ASP.NET 中控制器索引的调用者路由?

Posted

技术标签:

【中文标题】如何知道 ASP.NET 中控制器索引的调用者路由?【英文标题】:How to know the caller route for Index of a controller in ASP.NET? 【发布时间】:2022-01-17 04:06:25 【问题描述】:

所以我的 cshmtl 中有这样的东西:

<div>
    <a href="/cars"></a>
</div>
<div>
    <a href="/bikes"></a>
</div>

所以它转到汽车控制器并点击以下功能:

[HttpGet]
[Route("cars")]
[Route("bikes")]
public ActionResult Index()

    //here I want to set up if else depending on if cars got called or bikes
    return View();

在 index 函数中,我想通过一些 if else 知道调用了哪个路由。也许使用视图包之类的?

【问题讨论】:

这能回答你的问题吗? How do I get the full url of the page I am on in C# 我需要不同的逻辑,然后使用不同的操作。将共性重构为单独的方法 【参考方案1】:

请求上下文应该包含您需要的所有信息。

[HttpGet]
[Route("cars")]
[Route("bikes")]
public ActionResult Index()

    var requestUri = Context.Request.Url.AbsoluteUri;

    return View();

以下是相关文档页面:

https://docs.microsoft.com/en-us/dotnet/api/system.web.httpcontext?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.web.httprequest?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.uri?view=netframework-4.8

【讨论】:

以上是关于如何知道 ASP.NET 中控制器索引的调用者路由?的主要内容,如果未能解决你的问题,请参考以下文章