Maintaining Operation Id Through a Request in Web API - c#

It is not uncommon in a RESTful setting for the client to sent an operation id (typically a GUID) so that the request logs can be traced.
My question is, in Web API, is there a way native to .NET Web API to track the id per request?
log4net has LogicalContext that could track that. The problem with LogicalContext is that it is specific to log4net and cannot be used with NLog. There is no way in LogicalContext to get the list of all keys. I have to know the key before hand, which cases a problem if one API calls it "operation id" and another API calls it "activity id".

Maybe use the Guid 'Trace.CorrelationManager.ActivityId' for CorrelationId ?
It can be configured per request in your application-class (inherits from System.Web.HttpApplication) using the method Application_BeginRequest.
https://github.com/NLog/NLog/wiki/Trace-Activity-Id-Layout-Renderer

Related

How to get the value of properties from Serilog Enrichers inside a controller method

I have an ASP.NET Web API project that uses Serilog with the Correlation Id enricher. It works fine for HTTP requests, but I have a few controller endpoints that queue a job for a dedicated async worker to handle when it's free (using Microsoft.Extensions.Hosting.IHostedService). The issue is since these jobs get picked up outside of the initial HTTP request block, they lose the Correlation Id. I know I can push a property to the Logger Context using:
Serilog.Context.LogContext.PushProperty("CorrelationId", request.CorrelationId);
But I'm unsure how to get the existing correlation id that's used in the initial HTTP request. If I do, I can send it in the job metadata to be used with the async jobs later. Any ideas?

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?
You can try to use this open source component on github to solve your problem 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.

How to include Http request method name in client method names generated with NSwag

When I generate a C# client for an API using NSwag,
where the API includes endpoints that can be used with multiple Http request types (e.g. POST, GET)
the client generates a method for each request with the same base name, plus a number.
E.g. Using this API: https://api.premiumfunding.net.au/assets/scripts/swagger/v1/swagger.json
The schema contains an endpoint /contract that supports GET and POST requests, and an endpoint /contract/{ID} that supports GET, POST and DELETE requests.
The generated client has methods:
ContractAsync for GET requests without ID
Contract2Async for POST requests without ID
Contract3Async for GET requests with ID
Contract4Async for POST requests with ID
Contract5Async for DELETE requests with ID
I would like it to generate methods named:
GetContractAsync for GET requests without ID
PostContractAsync for POST requests without ID
GetContractAsync for GET requests with ID (method overload)
PostContractAsync for POST requests with ID (method overload)
DeleteContractAsync for DELETE requests with ID
At the moment I am just renaming the methods manually.
Is it possible to configure NSwag to generated these method names?
(Or is there an alternative tool that will give me this result?)
You can implement and provide an own IOperationNameGenerator:
https://github.com/RSuter/NSwag/blob/master/src/NSwag.CodeGeneration/OperationNameGenerators/IOperationNameGenerator.cs
Another option would be to preprocess the spec and change the “operationId”s to the form “controller_operation” (simple console app based on the NSwag.Core package)

RESTful URL for RPC-like operation

I'm implementing a RESTful API for a DVD rental website using ASP.NET Web API. The domain model (simplified) consists of Customer and Subscription entities. A customer has an associated subscription.
Most of the operations exposed by the API are simple CRUD operations, which are easy enough to model according to RESTful principles. E.g.
GET /api/subscriptions/1 - get subscription with id 1
POST /api/subscriptions - add a new subscription
PUT /api/customers/2 - update customer with id 2 with contents of PUT body
There is a requirement to periodically check for expired subscriptions, by comparing the EndDate field on each Subscription entity read from our database with the current date. For each subscription that has expired, the CustomerStatus field of the associated customer should be set to Archived and an email sent to the customer. The operation will be exposed through our REST API and invoked daily from an external service.
What URL scheme should I use to expose this operation according to RESTful principles? My first thought is that it's a PUT operation on api/customers/{SomeResource} as it potentially involves updating the CustomerStatus field of zero or more customers and is also an idempotent operation.
For example:
PUT /api/customers/expired
Does this sound reasonable?
Note that there is no body sent in this request, as the customers whose statues are being updated are queried from a database rather than being supplied by the end user. My understanding is that a PUT request doesn't have to include a body.
This is almost certainly a POST operation.
However, I question the design of your service. Why does the behaviour you describe need to be externally-controlled by way of a RESTful API? If the exact timing and nature of the operation is known beforehand, why not use some other means of scheduling the job...a means that is more straightforward and wouldn't raise these kinds of questions?
Ref: Stack Overflow
Edit: note that the operation described by the OP is not idempotent and thus not a qualifying PUT operation.
Additional edit: note that the .Net framework uses the POST method by default for service endpoints marked with the WebInvoke attribute. Per the documentation for this attribute, it represents an endpoint that "is logically an invoke operation". To me, this reads like a remote procedure call (i.e. RPC).

Authentication via headers in WCF REST service

I am new to WCF services and currently testing out things.
I have got a little REST API, which has several methods. Some of them require a user context (session), some others don't. At login, each user gets a session token. The client should supply this token and his user ID on every request via HTTP headers.
At the moment, I wrote a method for getting those two headers and validate the session, calling it on every method which will need a user context. This seems kinda nasty if the API gets bigger.
Is there a better approach for doing this?
You can leverage of following solutions:
Custom class deriving IClientMessageInspector/IDispatchMessageInspector for client and service respectively. Then you add its instance to MessageInspectors. Advantage of having messageInspector is that it's applied to single endpoint so regardless of having many endpoints exposed (both SOAP and REST), messageInspector can be associated only with single one. Whenever message is either received or sent, AfterReceive or BeforeSent method is invoked respectively. There you retrieve headers and if token does not match any expected you can throw an exception. Such a way out provides separation between exposed contract and background checks such as token validation.
Custom class deriving IOperationInvoker. Within custom operation invoker you explicitly call method and thanks to it you can examine headers (OperationContext.Current.IncomingMessage) before any method gets invoced.
I brought up only concepts, extensive information and examples can be looked up on Internet.

Categories