How to generate a URL for ASP.NET MVC action, including hostname and port?

My current request is:

http://www.mofeng.com:4355/

I want display an action url in asp.net view layer, url is like this(full url, including http://protocol + hostname + port + controllerName + actionName):

http://www.mofeng.com:4355/controllerX/actionY

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

enter image description here

Url.Action("Action", "Controller", null, Request.Url.Scheme);

How to include the following in the Form Action attribute?

1. Protocol(http:// or https://)
2. HostName

3. QueryString

4. Port

@{
    var actionURL = Url.Action("Action", "Controller", 
                               FormMethod.Post, Request.Url.Scheme)  
                    + Request.Url.PathAndQuery;
}
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, 
                                                   new { @action = actionURL }))
{
}

Method 2

besides the default route:

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Application", action = "Index", id = UrlParameter.Optional }
        );

you may need to implement a new one :

        routes.MapRoute(
            name: "ControllerXActionYRoute",
            url: "controllerX/actionY",
            defaults: new { controller = "controllerX", action = "actionY" }
        );

and then you can use :

<div>@Url.Action("Action", "Controller", null, Request.Url.Scheme);</div>

*EDIT: *

to get the full url you must go to absolute.

<div>VirtualPathUtility.ToAbsolute(@Url.Action("Action", "Controller"));</div>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x