Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the Name parameter in HttpPostAttribute

I am seeing the following code being applied in .net core action methods:

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

What is the purpose of the "Name" parameter in the HttpPost attribute?

like image 577
Sharath Avatar asked Oct 22 '19 05:10

Sharath


2 Answers

The Name property is used for Url Generation. It has nothing to do with routing! You can omit it almost all the time.

Add the following code to your controller and you will get the "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}";
}

The Name property in the first action, when used, for example, to generate a url, is merely used to reference the action yyy. In my set up, invoking /api/test returns the string The url of Route Name xxx is https://localhost:44384/api/qqq.

Action yyy is reachable by the route .../qqq, the first parameter passed to the HttpGet attribute constructor.

like image 173
Old Geezer Avatar answered Oct 15 '22 15:10

Old Geezer


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

Example usage; If you have two methods with the same name that take different parameters, you can use Name parameter to differentiate Action Names.

like image 30
Derviş Kayımbaşıoğlu Avatar answered Oct 15 '22 13:10

Derviş Kayımbaşıoğlu