我已按照this article中的说明使用ASP.NET MVC 5构建了RESTful Web API服务。作为流程的一部分,我设置了一个控制器:
[Route("api/[controller]")]
public class AccountController : Controller
{
[FromServices]
public IAccountRepository Repository { get; set; }
[HttpGet(Name = "GetAll")]
public IEnumerable<UserAccount> GetAll() {
return Repository.GetAll();
}
[HttpGet("(id)", Name = "GetUserAccount")]
public IActionResult GetUserAccount(int id) {
var account = Repository.GetUserAccount(id);
if (account == null)
return HttpNotFound();
return new ObjectResult(account);
}
[HttpPost("(item)", Name = "AddUserAccount")]
public IActionResult Add([FromBody] UserAccount item) {
if (item == null)
return HttpBadRequest();
return CreatedAtRoute("GetUserAccount", new { controller = "Account", id = item.Id }, item);
}
[HttpDelete( "(id)", Name = "RemoveUserAccount" )]
public void Remove(int id) {
Repository.Remove(id);
}
[HttpPost("(id)", Name = "UpdateUserAccount")]
public IActionResult Update([FromBody] UserAccount item) {
if (item == null)
return HttpBadRequest();
if (!Repository.Update(item))
return HttpNotFound();
return new NoContentResult();
}
}
当我使用URL http://localhost:2733/api/account从浏览器访问此服务时,执行`GetAll操作,这没关系,但是当我尝试使用URL http://localhost:2733/api/account/getall访问它时,我得到了404错误。
我做错了什么?
答案 0 :(得分:0)
我通过更改控制器中的方法来使其工作,因此它们与默认值控制器中的签名匹配。控制器类现在看起来像:
[Route("api/[controller]")]
public class AccountController : Controller
{
[FromServices]
public IAccountRepository Repository { get; set; }
[HttpGet]
public IEnumerable<UserAccount> Get() {
return Repository.GetAll();
}
[HttpGet("{id}")]
public IActionResult Get(int id) {
var account = Repository.GetUserAccount(id);
if (account == null)
return HttpNotFound();
return new ObjectResult(account);
}
[HttpPost]
public IActionResult Post([FromBody] UserAccount item) {
if (item == null)
return HttpBadRequest();
var account = Repository.Add(item);
return new ObjectResult(account);
}
[HttpDelete("{id}")]
public void Delete(int id) {
Repository.Remove(id);
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] UserAccount item) {
if (item == null)
return HttpBadRequest();
if (!Repository.Update(item))
return HttpNotFound();
return new ObjectResult(item);
}
}
我学到的另一件事是,为了配置MVC路由,Startup.cs中的Startup
类需要ConfigureServices
方法中的以下行:
services.AddMvc();
它还需要Configure
方法中的这一行:
app.UseMvc();
通过这些更改,控制器可以将请求路由到正确的方法。