我正在构建一个 ASP.NET Core 2.0 WEB API。我的 Controller 有几种方法。但是,当我从 Postman 调用时,所有方法都不起作用。它一直表现得像 HTTP(获取、放置、发布和删除)动词。那么,我怎样才能从客户端调用我想要的方法。或者,可以这样服务吗?
这是我的代码:
namespace DutchTreat.Controllers
{
[Route("api/[controller]")]
public class OrdersController : Controller
{
private readonly IDutchRepository _ctx;
private readonly ILogger<OrdersController> _logger;
public OrdersController(IDutchRepository _ctx, ILogger<OrdersController> logger)
{
this._ctx = _ctx;
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
try
{
return Ok(_ctx.GeAllOrders());
}
catch (Exception e)
{
return BadRequest("Something Went Wrong");
}
}
[HttpGet("{id:int}")]
public IActionResult GetOrdersById(int id)
{
try
{
var orders = _ctx.GetOrdersById(id);
if (orders != null)
return Ok(orders);
else
return NotFound();
}
catch (Exception e)
{
return BadRequest("Something Went Wrong");
}
}
[HttpPost]
public IActionResult Post(Order model)
{
try
{
_ctx.AddEntity(model);
_ctx.SaveChanges();
return Created($"/api/orders/{model.Id}", model);
}
catch (Exception e)
{
return BadRequest("Something Went Wrong");
}
}
public IActionResult SampleMethod()
{
// Sample Method Definition
return null;
}
}
}
我向 postman 请求:http://localhost:8888/api/orders/SampleMethod 它显示404 未找到!
最佳答案
SampleMethod
缺少路由属性,这就是它在调用时显示 404 Not Found 的原因。
更新操作以使用适当定义的路由模板和HTTP{Verb}
以下示例为操作定义了 HTTP GET。
//GET api/orders/SampleMethod
[HttpGet("SampleMethod")]
public IActionResult SampleMethod() {
// Sample Method Definition
return Ok();
}
关于c# - 在 ASP.NET WEB API Controller 中,所有方法都充当 HTTP 动词(Get、Put、Post 和 Delete),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719106/