1

I got the following code inherited from another developer an I am trying to understand it,what do the square brackets [] stand for?why do some have 'HttpPost' and some 'HttpGet'

namespace webService.Controllers.Scheduler
{
    public class testbedsController : EntityController<testbedsService, testbeds>
    {
        testbedsService p = new testbedsService();
        [Route("api/testbeds/")]
        [HttpPost]
        public testbeds AddOrUpdate(testbeds testbedsInformation)
        {
            try
            {

                return p.AddOrUpdate(testbedsInformation);
            }
            catch (Exception e)
            {                
                throw new Exception(e.ToString());
            }
        }
}
user3508811
  • 847
  • 4
  • 19
  • 43
  • Its an [Attribute](http://stackoverflow.com/questions/20346/net-what-are-attributes) –  Dec 16 '16 at 23:56
  • whats the significance of the square brackets around it?is there one or its just syntax?why do some have 'HttpPost' and some 'HttpGet' – user3508811 Dec 16 '16 at 23:58
  • 1
    That's just how the compiler knows that its an attribute (Metadata applied to the method). And [HttpGet](https://msdn.microsoft.com/en-us/library/system.web.mvc.httpgetattribute(v=vs.118).aspx) and [HttpPost](https://msdn.microsoft.com/en-us/library/system.web.mvc.httppostattribute(v=vs.118).aspx) are filter attributes that determine if the method can be called as a get or a post. –  Dec 17 '16 at 00:01

1 Answers1

1

The square brackets denote a C# "attribute". They enable specifying additional data about something such as a method. See more info here: Attributes in C#

The HttpGet, HttpPost, and Route attributes (among others) can specify the following:

  1. The URL that you use to call the MVC action method
  2. The allowed HTTP methods for the MVC action method

In this particular case:

  • [Route("api/testbeds/")] --> This specifies that the URL for this action is api/testbeds/, so you would access this via http://my-server/api/testbeds/.
  • [HttpPost] --> This doesn't specify a URL, but it specifies that only the HTTP "POST" verb is allowed (so not GET, PUT, DELETE, etc.)
Community
  • 1
  • 1
Eilon
  • 25,582
  • 3
  • 84
  • 102