您必须在控制器方法中命名参数,因为它们在路由配置中命名。因此,将其命名为id
:
[HttpPut]
public string Method(int id)
{
return "";
}
[HttpGet]
public string Method(int id)
{
return "";
}
...或者,在路由配置中更改它:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{a}",
defaults: new { a = RouteParameter.Optional }
);
}
请注意,它现在配置为a
而不是id
更新
以下是适用于上述配置的路由的控制器方法:
// Example URI: http://localhost:62536/api/Controller/PutMethod/10
[HttpPut]
public string PutMethod(int a)
{
return a.ToString();
}
// Example URI: http://localhost:62536/api/Controller/GetMethod/10
[HttpGet]
public string GetMethod(int a)
{
return a.ToString();
}
// Example URI: http://localhost:62536/api/Controller/PutMethod/
[HttpPut]
public string PutMethod()
{
return "(none)";
}
// Example URI: http://localhost:62536/api/Controller/GetMethod/
[HttpGet]
public string GetMethod()
{
return "(none)";
}
GET、PUT、POST、DELETE HTTP 动词的使用
本质上,RESTful API 设计围绕着对业务/应用程序域建模的资源、寻址它们的 URI 以及四个基本操作 GET、PUT、POST、DELETE(有时是第 5 个,PATCH)。例如,在人力资源应用程序域中,我们有员工。我们可以将员工集合表示为由 URI http://example.com/api/Employees寻址的资源,并将集合中的每个员工表示为由 URI http://example.com/api/Employee寻址的资源/ id,其中id是员工的 ID。所以,我们可以:
如果路由配置如下:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",i
defaults: new { id = RouteParameter.Optional }
);
}
员工的控制者可以是:
public class EmployeesController : ApiController
{
// GET api/Employees
public IEnumerable<Employee> Get()
{
List<Employee> employees = null;
// Get here the list of employees
return employees;
}
// POST api/Employees
public int Post(Employee employee)
{
// Persist here the new employee and determine its ID (for example, identity in SQL Server)
return employee.Id; // Returns the ID of the newly created employee
}
// GET api/Employees/5
public Employee Get(int id)
{
Employee employee;
// Get here the employee with the id
return employee;
}
// PUT api/Employees/5
public Employee Put(int id, Employee employee)
{
var updatedEmployee;
// Find existing employee with the id, update it with the data passed via employee argument and persist it
return updatedEmployee; // It's a good practice to return the updated entity back, especially in the case when updating changes some properties, e.g. summarized values, counts, etc.
}
// DELETE api/Employees/5
// More complicated example showing communicating statuses back to the client regarding successfulness of the operation
public IHttpAction Delete(int id)
{
Employee employee;
// Find the employee with the id
if (employee == null)
return NotFound(); // The employee is not found. Signal 404, i.e. there's no resource at this URI.
// Delete here the employee from the persistence mechanism
return Ok(); // The employee is found and deleted. Signal 200 - OK
}
}
请注意,不需要 attributes [HttpGet]
,[HttpPut]
等。它只是按照惯例工作。
当然,这是一个过于简单化的例子,只是为了传达这一点。
希望能帮助到你。