【问题标题】:What is the purpose of the Name parameter in HttpPostAttributeHttpPostAttribute 中 Name 参数的作用是什么
【发布时间】:2020-02-18 05:19:38
【问题描述】:

我看到在 .net 核心操作方法中应用了以下代码:

[HttpPost("MyAction", Name = "MyAction")]
public IActionResult MyAction()
{
    // some code here
}

HttpPost 属性中“Name”参数的作用是什么?

【问题讨论】:

标签: c# asp.net-core actionmethod


【解决方案1】:

From the source

    /// <summary>
    /// Gets the route name. The route name can be used to generate a link using a specific route, instead
    ///  of relying on selection of a route based on the given set of route values.
    /// </summary>
    string Name { get; }

示例用法;如果你有两个同名的方法接受不同的参数,你可以使用Name参数来区分Action Names。

【讨论】:

    【解决方案2】:

    来自document

    路由名称可用于根据特定路由生成 URL。路由名称对路由的 URL 匹配行为没有影响,仅用于 URL 生成。路由名称在应用程序范围内必须是唯一的。

    它可用于根据特定路由生成 URL。例如,路由定义如下:

    [HttpGet("{id}", Name = "GetContact")]
    public IActionResult GetById(string id)
    {
        var contact = contactRepository.Get(id);
        if (contact == null)
        {
            return NotFound();
        }
        return new ObjectResult(contact);
    }
    

    您可以使用CreatedAtRoute 方法返回新联系人的内容及其URI。 CreatedAtRoute 方法将根据路由名称“GetContact”和 id 生成 URI:

    [HttpPost]
    public IActionResult Create([FromBody] Contact contact)
    {
        if (contact == null)
        {
            return BadRequest();
        }
        contactRepository.Add(contact);
        return CreatedAtRoute("GetContact", new { id = contact.ContactId }, contact);
    }
    

    【讨论】:

      【解决方案3】:

      Name 属性用于 Url Generation。跟路由没有关系!您几乎可以一直省略它。

      将以下代码添加到您的控制器中,您将获得“啊哈!”:

      [HttpGet("qqq", Name = "xxx")]
      public string yyy()
      {
         return "This is the action yyy";
      }
      
      [HttpGet("test")]
      public string test()
      {
          var url = Url.Link("xxx", null);  //Mine is https://localhost:44384/api/qqq
          return $"The url of Route Name xxx is {url}";
      }
      

      第一个动作中的Name 属性,例如用于生成url 时,仅用于引用动作yyy。在我的设置中,调用 /api/test 返回字符串 The url of Route Name xxx is https://localhost:44384/api/qqq

      动作yyy 可通过路由 .../qqq 到达,这是传递给HttpGet 属性构造函数的第一个参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-24
        • 2015-09-26
        • 2015-12-18
        • 2021-04-09
        • 1970-01-01
        • 2018-06-03
        • 2011-11-25
        • 1970-01-01
        相关资源
        最近更新 更多