ASP.NET Web API generate url using Url.Action

后端 未结 2 861
暖寄归人
暖寄归人 2020-12-24 11:02

How can I generate the same url but in Web Api ?

var url = Url.Action(\"Action\", \"Controller\", new { product = product.Id, price = price }, protocol: Requ         


        
相关标签:
2条回答
  • 2020-12-24 11:39

    This expands on the answer by VictorBahtev to mention ASP.NET CORE.

    In 2020 there is a chance that your project is targeting ASP.NET Core 3.1. In the current version of WebAPI there is a method available to do the trick requested exactly by the OP. The method below doesn't require a route parameter (which OP didn't provide):

    string url = this.Url.ActionLink("ActionName", "ControllerName", new { product = product.Id, price = price, ..}[, protocol = null, host = null, string fragment = null]);
    
    0 讨论(0)
  • 2020-12-24 11:46

    Maybe the closest helper to Url.Action in Web Api Controller is the Url.Link method which will generate the url by Route name, Controller Name, Action Name and the route parameters (if needed).

    Here is a simple example

    The default App_start/RouteConfig.cs

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

    The Web Api Controller:

    public class MyWebApiController : ApiController
    {
        public string Get()
        {
            var url = this.Url.Link("Default", new { Controller = "MyMvc", Action = "MyAction", param1 = 1, param2 = "somestring" });
            return url;
        }
    }
    

    The MVC Controller

    public class MyMvcController : Controller
    {
        public ActionResult MyAction(int param1, string param2)
        {
            // ...
        }
    }
    

    The generated url by the WebApi controller will be http://myDomain/MyMvc/MyAction?param1=1&param2=somestring.

    I didn't find how to pass the protocol/url schema but at the and it will be just a string and you can manipulate it if you know what the protocol should be.

    Hope this helps.

    EDIT:

    This may help for the protocol part: Generate HTTPS link in Web API using Url.Link

    0 讨论(0)
提交回复
热议问题