6.42HttpContext 转发的优势

创建于 2026 年 8 月 17 日约 1 分钟读完

在对接第三方 API 接口时,通常的做法是创建一个入口程序,并在其中调用 HTTP 远程请求服务来发送请求到指定的第三方接口。假设第三方接口的控制器定义如下:

cs
[ApiController][Route("[controller]/[action]")]public class VendorController : ControllerBase{    [HttpPost]    public VendorModel Add(VendorModel model)    {        return model;    }}

传统的做法是使用 HTTP 远程请求服务来发送请求,例如:

cs
[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())        );    }}

然而,使用 HttpContext 转发功能后,我们可以简化代码,只需创建与第三方接口一致的接口控制器声明,例如 VendorControllerAdd 方法,如下所示:

cs
[ApiController][Route("[controller]/[action]")]public class YourController(IHttpContextAccessor httpContextAccessor) : ControllerBase{    [HttpPost]    public async Task<VendorModel> AddAsync(VendorModel model)  // 同步和异步都行    {        // 自动转发 model,无需任何设置        return await httpContextAccessor.Context            .ForwardAsync<VendorModel>("https://www.furion.net/vendor/add");    }}

通过这种方式,代码变得更加简洁明了,无需手动构建和发送 HTTP 请求,而是利用 HttpContext 转发功能直接调用第三方接口。