6.42Advantages of HttpContext Forwarding
When integrating with third-party API endpoints, the common approach is to create an entry program and call the HTTP remote request service within it to send requests to the specified third-party endpoint. Assume the third-party endpoint's controller is defined as follows:
[ApiController][Route("[controller]/[action]")]public class VendorController : ControllerBase{ [HttpPost] public VendorModel Add(VendorModel model) { return model; }}The traditional approach is to use the HTTP remote request service to send the request, for example:
[ApiController][Route("[controller]/[action]")]public class YourController(IHttpRemoteService httpRemoteService) : ControllerBase{ [HttpPost] public async Task<VendorModel> AddVendorAsync() { return await httpRemoteService.SendAsync<VendorModel>( HttpRequestBuilder.Post("https://www.furion.net/vendor/add") .SetJsonContent(new VendorModel()) ); }}However, by using the HttpContext forwarding feature, we can simplify the code. We only need to create a controller declaration that matches the third-party endpoint's interface, such as the Add method of VendorController, as shown below:
[ApiController][Route("[controller]/[action]")]public class YourController(IHttpContextAccessor httpContextAccessor) : ControllerBase{ [HttpPost] public async Task<VendorModel> AddAsync(VendorModel model) // Both synchronous and asynchronous are supported { // Automatically forwards the model, no additional setup required return await httpContextAccessor.Context .ForwardAsync<VendorModel>("https://www.furion.net/vendor/add"); }}In this way, the code becomes more concise and clear. Instead of manually building and sending the HTTP request, we leverage the HttpContext forwarding feature to directly invoke the third-party endpoint.