简体   繁体   中英

How to implement Idempotent key into an asp.net web api?

An app makes an HTTP post with Idempotency Key in the API request header.

On the server-side, you want to check if the request with the Idempotent Key has been processed for this client or not.

  • If the request has not been processed than we proceed with the method to CREATE, UPDATE or DELETE.
  • If the Idempotent Key has been used in the previous request, then we response back to the client with an error message.

How do we track the API request, the API count, and the Idempotent Key used in request etc?

By logging all API request in the database and make a round trip to the database to check this information everytime a new request is made? Or is there a better way?

你可以尝试使用github上的这个开源组件来解决你的问题IdempotentAPI

What I like doing in a fairly standard setup (database, EF core, web api) is use a middleware to add ( Context.Add() ) the idempotency key to the database without committing .

Later on, in the controller, a service or some sort of handler, I make sure Context.SaveChanges() (or UnitOfWork.Commit() ) is called only once (which should normally be the case since you're supposed to update only 1 aggregate root per transaction).

This way you're sure you're saving atomically, your idempotency key will only be saved if your insert/update/delete is successful. If the idempotency key already exists in the database your insert/update/delete will fail.

Finally, what you can also do is cache your successful responses, so that in case of idempotency exception, you can simply return the cached response.

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