简体   繁体   中英

All methods act as a HTTP verb (Get, Put, Post And Delete) in ASP.NET WEB API controller

I am building up a ASP.NET Core 2.0 WEB API . My controller has several methods. But, all the methods are not working when I am calling from Postman. All the time it behaves like HTTP (Get, Put, Post And Delete) verbs. So, how can I call my desired methods from client side. Or, is it okay to serve this way?

Here is my code:

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

And I am requesting from Postman: http://localhost:8888/api/orders/SampleMethod It shows 404 not found !

SampleMethod is missing routing attributes, which is why it shows 404 Not Found when called.

Update action to use an appropriately defined route template and HTTP{Verb}

The following example defines an HTTP GET for the action.

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

    return Ok();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM