Getting full URL of action in ASP.NET MVC

This question already has an answer here:

  • How do I find the absolute url of an action in ASP.NET MVC? 9 answers

  • There is an overload of Url.Action that takes your desired protocol (eg http, https) as an argument - if you specify this, you get a fully qualified URL.

    Here's an example that uses the protocol of the current request in an action method:

    var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);
    

    HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:

    <span>
      Copy
      <a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a> 
      and post it anywhere on the internet!
    </span>
    

    As Paddy mentioned: if you use an overload of UrlHelper.Action() that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.

    I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:

    /// <summary>
    /// Generates a fully qualified URL to an action method by using
    /// the specified action name, controller name and route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="actionName">The name of the action method.</param>
    /// <param name="controllerName">The name of the controller.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteAction(this UrlHelper url,
        string actionName, string controllerName, object routeValues = null)
    {
        string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
    
        return url.Action(actionName, controllerName, routeValues, scheme);
    }
    

    You can then simply use it like that in your view:

    @Url.AbsoluteAction("Action", "Controller")
    

    这是你需要做的。

    @Url.Action(action,controller, null, Request.Url.Scheme)
    
    链接地址: http://www.djcxy.com/p/55698.html

    上一篇: ASP.Net MVC 3.0属性[OutputCache]

    下一篇: 在ASP.NET MVC中获取动作的完整URL