HttpPostAttribute 中 Name 参数的用途是什么

What is the purpose of the Name parameter in HttpPostAttribute

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

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

HttpPost 属性中 "Name" 参数的用途是什么?

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

用法示例;如果您有两个同名但参数不同的方法,您可以使用名称参数来区分操作名称。

来自 document :

Route names can be used to generate a URL based on a specific route. Route names have no impact on the URL matching behavior of routing and are only used for URL generation. Route names must be unique application-wide.

可用于根据特定路线生成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方法return新联系人的内容以及它的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);
}

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

将以下代码添加到您的控制器中,您将获得 "Aha!":

[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 returns 字符串 The url of Route Name xxx is https://localhost:44384/api/qqq.

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