我有一个简单的CRUD操作控制器。所有操作都可以使用名为Delete的最后一个操作,即HTTP DELETE操作。当我尝试使用示例url调用删除操作时:
然后应用程序返回404 Not Found并且操作未触发。
在我的其他控制器中,删除操作正常工作。一个区别是,在其他控制器中,我在控制器上有一个路由属性而不是每个操作。这是一个问题?
public class AttendancesController : Controller
{
public AttendancesController(IGroupService groupService, IAttendanceService attendanceService, IPersonService personService, IPersonAttendanceService personAttendanceService)
{
//
}
[Route("api/groups/{groupId}/[controller]")]
[HttpGet]
public IActionResult GetAttendancesForGroup(int groupId)
{
//
}
[Route("api/groups/{groupId}/[controller]/{date}")]
[HttpGet]
public IActionResult GetAttendanceForGroup(int groupId, DateTime date)
{
//
}
[Route("api/groups/{groupId}/[controller]")]
[HttpPost]
public IActionResult CreateAttendanceForGroup(int groupId, [FromBody] AttendanceCreateDto dto)
{
//
}
[Route("api/people/{personId}/[controller]")]
[HttpGet]
public IActionResult GetAttendancesForPerson(int personId)
{
//
}
[Route("api/groups/{groupId}/[controller]")]
[HttpDelete("{id}")]
public IActionResult Delete(int groupId, int id)
{
var group = _groupService.FindById(groupId);
if (group == null)
return NotFound();
var attendance = _attendanceService.GetAttendanceByIdAndGroupId(id,groupId);
if (attendance == null)
return NotFound();
_attendanceService.Delete(attendance);
return NoContent();
}
}
答案 0 :(得分:6)
我不明白为什么在这种情况下[HttpDelete(“{id}”)]会被忽略。
你正在混合路线。
按如下方式重构该类。
将公共路由添加到控制器作为路由前缀,并利用路由约束
[Route("api/groups/{groupId}/[controller]")]
public class AttendancesController : Controller {
public AttendancesController(IGroupService groupService, IAttendanceService attendanceService, IPersonService personService, IPersonAttendanceService personAttendanceService) {
//
}
[HttpGet] // Matches GET api/groups/1/attendances
public IActionResult GetAttendancesForGroup(int groupId) {
//
}
[HttpGet("{date:datetime}")] //Matches GET api/groups/1/attendances/2017-05-27
public IActionResult GetAttendanceForGroup(int groupId, DateTime date) {
//
}
[HttpPost] // Matches POST api/groups/1/attendances
public IActionResult CreateAttendanceForGroup(int groupId, [FromBody] AttendanceCreateDto dto) {
//
}
[HttpGet("~/api/people/{personId}/[controller]")] // Matches GET api/people/1/attendances
public IActionResult GetAttendancesForPerson(int personId) {
//
}
[HttpDelete("{id:int}")] // Matches DELETE api/groups/1/attendances/10
public IActionResult Delete(int groupId, int id) {
var group = _groupService.FindById(groupId);
if (group == null)
return NotFound();
var attendance = _attendanceService.GetAttendanceByIdAndGroupId(id,groupId);
if (attendance == null)
return NotFound();
_attendanceService.Delete(attendance);
return NoContent();
}
}