I'm using an nSwag generated client to call an API that requires a bearer token to be passed in.
I've setup my client the same as this answer https://stackoverflow.com/a/49801655/3953989
I'm calling SetBearerToken()
in my BaseController's OnActionExecuting()
and pulling my stored bearer token from a cookie.
BaseController.cs
public class BaseController : Controller
{
protected IApiClient ApiClient;
public BaseController(IApiClient apiClient)
{
ApiClient = apiClient;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!string.IsNullOrWhiteSpace(CookieData?.Token))
{
ApiClient.SetBearerToken(CookieData.Token);
}
base.OnActionExecuting(context);
}
}
I also have my ApiClient setup for DI
Startup.cs
services.AddHttpClient<IApiClient, ApiClient>(client =>
{
client.BaseAddress = new Uri(appSettings.Value.ApiBaseUrl);
});
This works OK for controllers since HttpContext
is available during OnActionExecuting()
but there's no equivalent for ViewComponents.
- How would I set my bearer token in a ViewComponent?
- I also would like to know how I should deal with this in libraries that I create in a controllers constructor.
TestController.cs
public class TestController : BaseController
{
private readonly IUserService _userService;
public TestController(IApiClient apiClient) : base(apiClient)
{
var cookieData = HttpContext..... // HttpContext is null here
apiClient.SetBearerToken(cookieData.Token)
_userService = new UserService(apiClient);
}
}