ASP.NET Web API generate url using Url.Action

回眸只為那壹抹淺笑 提交于 2019-12-03 04:43:55

问题


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

var url = Url.Action("Action", "Controller", new { product = product.Id, price = price }, protocol: Request.Url.Scheme);

P.S.

The url should be generated to an MVC controller/action but from within web api.

So basically: make a get request to my api/generateurl and that will return an url to :

http://domain.com/controller/action?product=productId&price=100

回答1:


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



来源:https://stackoverflow.com/questions/25245065/asp-net-web-api-generate-url-using-url-action

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