简体   繁体   中英

Shared logic for Multiple HttpPost method in Web API controller

I have Multiple HttpPost methods in Web API controller and I also need to check for certain conditions for all of them. how can i add this logic in the controller without repeating the code in each method? example:

public class OnboardingController : ApiController
// can i check for conditions before the code enters to any of the httpPost?

[HttpPost]
[Route("api/Onboarding/Method1", Name = "Onboarding/Method1")]

// some code

[HttpPost]
[Route("api/Onboarding/Method2", Name = "Onboarding/Method2")]

// some code

This can be achieved with filters. They allow you to intercept requests and perform some actions before control is passed to controllers and their methods. Eg, you can log request parameters or return 403 Not Authorized if a user has no access the requested endpoint.

There are few built-in filters and you can also create your own filters.

Read more about filters: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0

This article shows how to use built-in Authorize filter: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/simple?view=aspnetcore-6.0

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