MVC路由属性方括号
问题描述:
我从另一个开发继承下面的代码我试图去理解它,什么做square brackets []
立场?为什么有的有“HttpPost”和一些“HTTPGET”MVC路由属性方括号
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());
}
}
}
答
方括号表示C#“属性”。它们可以指定关于诸如方法的其他数据。在这里看到更多的信息:Attributes in C#
的HttpGet
,HttpPost
,并Route
属性(等等)可以指定如下:
- 您使用调用MVC操作方法
- 允许的HTTP网址用于MVC的操作方法
方法在这种特定的情况下:
-
[Route("api/testbeds/")]
- >这指定此操作的URL为api/testbeds/
,因此您可以通过http://my-server/api/testbeds/
访问此操作。 -
[HttpPost]
- >这不指定URL,但它指定只HTTP “POST” 动词被允许(这样没有GET,PUT,DELETE等)
它的一个[属性] (http://stackoverflow.com/questions/20346/net-what-are-attributes) –
围绕它的方括号的意义是什么?是否有一个或它的正义语法?为什么有些人有'HttpPost'和一些' HttpGet' – user3508811
这就是编译器知道它的一个属性(应用于该方法的元数据)。和[HttpGet](https://msdn.microsoft.com/en-us/library/system.web.mvc.httpgetattribute(v = vs.118).aspx)和[HttpPost](https://msdn.microsoft .com/en-us/library/system.web.mvc.httppostattribute(v = vs.118).aspx)是确定该方法是否可以作为get或post调用的过滤器属性。 –