ASP.NET Web API 使用 Url.Action 生成 url [英] ASP.NET Web API generate url using Url.Action

查看:30
本文介绍了ASP.NET Web API 使用 Url.Action 生成 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成相同的 url 但在 Web Api 中?

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);

附言

url 应该生成到 MVC 控制器/操作,但来自 web api.

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

所以基本上:向我的 api/generateurl 发出一个 get 请求,这将返回一个 url 到:

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

推荐答案

也许 Web Api Controller 中最接近 Url.Action 的帮助器是 Url.Link 方法,它会通过 Route name、Controller Name、Action Name 和路由参数(如果需要).

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).

这是一个简单的例子

默认的 App_start/RouteConfig.cs

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

Web Api 控制器:

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

MVC 控制器

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

WebApi 控制器生成的 url 将是 http://myDomain/MyMvc/MyAction?param1=1&param2=somestring.

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

我没有找到如何传递协议/url 模式,但在 并且它只是一个字符串,如果您知道协议应该是什么,您就可以操作它.

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.

希望这会有所帮助.

这可能有助于协议部分:使用 Url.Link 在 Web API 中生成 HTTPS 链接

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

这篇关于ASP.NET Web API 使用 Url.Action 生成 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆