簡體   English   中英

如何在ASP.NET MVC中獲取不帶參數的Action的URL

[英]How to get the URL of the Action without parameters in ASP.NET MVC

我有一個ASP.NET MVC Web應用程序,它運行在IIS上的虛擬目錄中。 在應用程序中,我有一個Action,它接受一個名為Id的參數。

public class MyController : MyBaseController 
{
    public ActionResult MyAction(int id)
    {
        return View(id);
    }
}

當我使用參數123調用Action時,生成的URL如下所示:

http://mywebsite.net/MyProject/MyController/MyAction/123

基本控制器中 ,如何在沒有任何參數的情況下優雅地找到Action的URL? 我想要的字符串是: /MyProject/MyController/MyAction

關於此問題還有其他問題,但它們不包括這些案例。 例如, Request.Url.GetLeftPart仍然給我Id。

@ trashr0x的答案解決了問題的最大部分,但是錯過了MyProject部分,並且不需要字典來構造問題字符串。 這是一個簡單的解決方案:

var result = string.Join("/", new []{ 
    Request.ApplicationPath, 
    RouteData.Values["controller"], 
    RouteData.Values["action"] 
});

您是否指定在默認路由UrlParameter.Optional id設置為可選( UrlParameter.Optional )?

routes.MapRoute(
    // route name
    "Default",
    // url with parameters
    "{controller}/{action}/{id}",
    // default parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

更新#1:下面是兩個解決方案,一個用於id是查詢字符串( ?id={id} ),另一個用於當它是Uri/{id}/ )的一部分時:

var localPath = Request.Url.LocalPath;
// works with ?id=123
Debug.WriteLine("Request.Url.LocalPath: " + localPath);
// works with /123/
Debug.WriteLine("Remove with LastIndexOf: " + localPath.Remove(localPath.LastIndexOf('/') + 1));

更新#2:好的,所以這是另一個去吧。 它適用於所有場景( ?id= ?id=123//123/ ),我已將動作簽名中的Id更改為int? 而不是int (需要重構):

var mvcUrlPartsDict = new Dictionary<string, string>();
var routeValues = HttpContext.Request.RequestContext.RouteData.Values;

if (routeValues.ContainsKey("controller"))
{
    if (!mvcUrlPartsDict.ContainsKey("controller"))
    {
        mvcUrlPartsDict.Add("controller", string.IsNullOrEmpty(routeValues["controller"].ToString()) ? string.Empty : routeValues["controller"].ToString());
    }
}

if (routeValues.ContainsKey("action"))
{
    if (!mvcUrlPartsDict.ContainsKey("action"))
    {
        mvcUrlPartsDict.Add("action", string.IsNullOrEmpty(routeValues["action"].ToString()) ? string.Empty : routeValues["action"].ToString());
    }
}

if (routeValues.ContainsKey("id"))
{
    if (!mvcUrlPartsDict.ContainsKey("id"))
    {
        mvcUrlPartsDict.Add("id", string.IsNullOrEmpty(routeValues["id"].ToString()) ? string.Empty : routeValues["id"].ToString());
    }
}

var uri = string.Format("/{0}/{1}/", mvcUrlPartsDict["controller"], mvcUrlPartsDict["action"]);
Debug.WriteLine(uri);

您是否嘗試過以下方法:

string actionName = HttpContext.Request.RequestContext.RouteData.Values["Action"].ToString();
string controllerName = HttpContext.Request.RequestContext.RouteData.Values["Controller"].ToString();
var urlAction = Url.Action(actionName, controllerName, new { id = "" });

嘗試這個:

Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);

但如果沒有查詢字符串,這將給出錯誤

所以,您也可以直接嘗試:

Request.Url.AbsoluteUri

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM