简体   繁体   中英

Webapi and normal methods in the same controller?

With the introduction of the Apicontroller attribute in asp.net core 2.1, I wonder how do I get the api and normal methods to work in the same controller.

[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> SaveOrder(SaveOrderModel model)
    {
        //...
    }

    public async Task<IActionResult> CustomerOrders()
    {
       if (!User.IsInRole("Customer"))
          return Challenge();
       var customer = await _workContext.CurrentCustomer();

       var model = await orderModelFactory.PrepareCustomerOrderListModel();
       return View(model);
    }
}

I can call post method /api/order/saveorder but cannot run the https://example.com/order/customerorders .

It shows an exceptions: InvalidOperationException: Action '.CustomerOrders ' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.

If I remove [ApiController] and [Route("api/[controller]")] on the controller level and instead put on the method level, then it surely works. still don't know if there's any better hybrid solution for these methods as i want to use this new ApiController feature.

[Route("/api/controller/saveorder")]
public async Task<IActionResult> SaveOrder(SaveOrderModel model)

Any input is greatly appreciated.

You are saying, that you cannot call https://example.com/order/customerorders . In your [Route("api/[controller]")] you define, that all Methods inside this controller will be available at https://example.com/api/order/ .

So to call your method, you need to call https://example.com/api/order/customerorders .

If you want to stay with https://example.com/order/customerorders , you need to put the [Route] attributes at your methods:

[ApiController]
public class OrderController : ControllerBase
{
        [HttpPost("api/order")]
        public async Task<IActionResult> SaveOrder(SaveOrderModel model)
        {
            ...

        }

        [HttpGet("order/customerorders")]
        public async Task<IActionResult> CustomerOrders()
        {
           if (!User.IsInRole("Customer"))
              return Challenge();
           var customer = await _workContext.CurrentCustomer();

           var model = await orderModelFactory.PrepareCustomerOrderListModel();
           return View(model);
        }
}

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