gpt4 book ai didi

asp.net-mvc-routing - 在 MVC 6 Controller 中使用 urlhelper 生成链接 (vNext)

转载 作者:行者123 更新时间:2023-12-02 18:13:02 24 4
gpt4 key购买 nike

我正在尝试学习新的 MVC 6。我以前从未使用过 Microsoft MVC 框架。我正在尝试通过使用 Controller 的 URL (urlhelper) 添加指向 Controller 不同操作的链接(显示 API 功能的主 Controller )来增强简单的教程 Web API。但是当我使用时:

this.Url.Action("Get", new {id = id});

我得到一个带有 URL 的查询字符串。我想要一个更安静风格的网址。

我认为在使用属性路由时,我不必像在旧的 WebApi 教程中看到的那样映射特定的路由。

我必须绘制路线吗?我需要做什么才能获得更安静的 URL 样式?

最佳答案

您可以向 Controller 中的路由属性添加名称,然后使用扩展方法 IUrlHelper.RouteUrl生成 url。

例如,给定以下 Web API Controller :

[Route("api/[controller]")]
public class UsersController : Controller
{
// GET: api/users
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/users/5
[HttpGet("{id}", Name ="UsersGet")]
public string Get(int id)
{
return "value";
}

//additional methods...
}

您可以生成网址api/users/123对于特定的 get by id 操作,使用 @Url.RouteUrl("UsersGet", new { id = 123 }) .

使用Url.Action时出现的问题扩展方法是,如果您有一个像上面示例中那样的 Controller ,其中有 2 个名为“Get”的操作,则这将使用不带参数的操作的路由并生成 /api/Users?id=123 。但是,如果您评论该方法,您将看到 @Url.Action("Get", "Users", new { id = 123 })还为您提供了预期的网址。

关于asp.net-mvc-routing - 在 MVC 6 Controller 中使用 urlhelper 生成链接 (vNext),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31821941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com