How to get action url without parameters in ASP.NET MVC

I have an ASP.NET MVC web application that runs in an IIS virtual directory. In the application, I have an action that takes a parameter named Id.

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

When I call the action with parameter 123, the resulting URL looks like this:

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

In the base controller how can i find the action url without any parameters? The line I'm trying to get is:/MyProject/MyController/MyAction

Other questions are asked, but they do not cover these cases. For example, Request.Url.GetLeftPartit still gives me an identifier.

+4
source share
4 answers
Answer

@trashr0x , MyProject, . :

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

, 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);
+3

:

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 = "" });
+2

:

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

,

, :

Request.Url.AbsoluteUri
+1

Source: https://habr.com/ru/post/1648177/


All Articles