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

不问归期 提交于 2020-01-21 01:33:29

问题


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


回答1:


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 }))
{
}



回答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>


来源:https://stackoverflow.com/questions/18552760/how-to-generate-a-url-for-asp-net-mvc-action-including-hostname-and-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!