我如何通过IHttpClientFactory访问自己的受保护API

时间:2019-07-19 17:31:38

标签: asp.net-mvc asp.net-core dotnet-httpclient asp.net-core-2.1

我正在尝试通过IHttpClientFactory访问我自己的API,但是正被重定向到登录页面。我通过jquery遇到了同样的问题,但是当我包含凭据时,“ include”已修复。

这是针对c#/ asp.net核心2.1 MVC控制器的。我使用的是股票标识

我尝试构建标头以包括带有Basic的Authorization和包含我的username:password的base64编码的字符串。如果我允许匿名访问端点,则我的代码可以正常工作。

该表单位于剃须刀页面中,并在后期将请求主体中的对象发送到端点。如果我的端点没有[AllowAnonymous]属性,那么我将被重定向回登录名和/或收到400错误的请求

string contentJson = JsonConvert.SerializeObject(content);
HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Patch, baseUrl);
HttpClient client = _clientFactory.CreateClient();
httpRequest.Content = new StringContent(contentJson, Encoding.UTF8, "application/json-patch+json");
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json-patch+json"));
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{yourusername}:{yourpwd}")));
HttpResponseMessage response = await client.SendAsync(httpRequest);

0 个答案:

没有答案