The Service Agent is the proxy layer that encapsulates the invocation of the corresponding Service Interface layer.
This layer is code-generated and responsible for performing the HTTP request / response handling.
The TypedHttpClientBase
provides the core Service Agent functionality for invoking an API endpoint using HTTP:
GetAsync
- HTTPGET
- generally a Read (CRUD) operation.PutAsync
- HTTPPUT
- generally a Create (CRUD) operation.PostAsync
- HTTPPOST
- generally an Update (CRUD) replacement operation.PatchAsync
- HTTPPATCH
- generally an Update (CRUD) modification operation.Delete
- HTTPDELETE
- generally a Delete (CRUD) operation.
The following is generally performed for each:
Step | Description |
---|---|
Request |
Create the HttpRequestMessage . |
RequestUri |
Set the HttpRequestMessage.RequestUri including the query string. |
ETag |
Where there is an HttpRequestOptions.ETag this will result in an If-None-Match (GET ) or alternatively If-Match header. |
Serialize |
Serializes the entity (where specified) as JSON to the HttpRequestMessage.Content as applicable. |
Send |
Uses an underlying HttpClient to send the HttpRequestMessage using the specified HTTP Method. |
Response |
Accepts the corresponding HttpResponseMessage . |
StatusCode |
Where the HttpResponseMessage.IsSuccessStatusCode is true , will deserialize the JSON HttpResponseMessage.Content as the resulting entity; otherwise, will convert the HttpResponseMessage.StatusCode to the equivalent IExtendedException and throw. |
There is a generated class per Entity
named {Entity}Agent
. There is also a corresonding interface named I{Entity}Agent
generated so the likes of test mocking etc. can be employed. For example, if the entity is named Person
, there will be corresponding PersonAgent
and IPersonAgent
classes.
There are currently no opportunities for a developer to extend on the generated code; beyond amending the underlying code generation templates. This is by design to limit the introduction of business or data logic into this layer.
However, there will more often than not be the need to manipulte the request. For example, add the likes of the credentials for authentication as part of the request before send. There are multiple opportunities to perform this; select the best method based on the requirements:
DelegatingHandler
- allows standardized request logic to be used for anyHttpClient.SendAsync
. This article, and the two preceeding within, provide the details on how to achieve.- Fluent
OnBeforeRequest
- theDefaultOptions.OnBeforeRequest
fluent-style method can be used to set for the instance. - Override
OnBeforeRequest
- as the{Entity}Agent
is implemented as a partial class this can be extended by overridding the default protectedOnBeforeRequest
method and the requistite logic included.