所有方法都充当ASP.NET WEB API控制器中的HTTP动词(Get,Put,Post和Delete)

时间:2018-04-08 14:45:36

标签: c# api asp.net-core-webapi

我正在构建一个 ASP.NET Core 2.0 WEB API 。我的控制器有几种方法。但是,当我从Postman打电话时,所有的方法都不起作用。它一直表现得像HTTP(Get,Put,Post和Delete)动词。那么,我怎样才能从客户端调用我想要的方法。或者,可以这样服务吗?

这是我的代码:

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;
        }
    }
}

我要求邮递员:http://localhost:8888/api/orders/SampleMethod 它显示 404 not found

1 个答案:

答案 0 :(得分:1)

SampleMethod缺少路由属性,这就是为什么在调用时会显示 404 Not Found 的原因。

更新操作以使用适当定义的路线模板和 HTTP {动词}

以下示例为操作定义了HTTP GET。

//GET api/orders/SampleMethod 
[HttpGet("SampleMethod")]
public IActionResult SampleMethod() {
    // Sample Method Definition

    return Ok();
}