【发布时间】:2019-11-04 00:44:27
【问题描述】:
我是 .netcore 的新手,我正在研究在 docker 容器上运行的 web api,并且在使用 postman 时,web api 的工作非常好,可以输出结果。我想在 .netcore 中创建一个程序,调用 webapi 端点并获取响应并在其他端点中使用 MVC 中的特定响应。
解释如下。
admin 的默认用户名和密码是默认设置的,例如 username:admin , password: helloworld
. admin 首次登录 api 需要一个新的个人密码,如下图 Postman 所示。
登录接口为:localhost://..../v1/users/login
第一个问题是如何使用 .netcore 在 Authorization->BasicAuth 中给出值。 api 的主体如下图所示。
设置 new_password 后,api 的响应是一个令牌,如下所示。
然后在环境中使用特定令牌来创建用户。下面给出了更清晰问题的图像。
最后,令牌随后用于进行其他 API 调用,例如创建用户。
API: https://localhost/..../v1/users
图片如下。
作为 .netcore 语言的新手,我真的很难进行这种 API 调用,因为我尝试的大多数教程都是从 API 生成自己的令牌,但在这里我只想获取响应令牌并保存然后在其他 API 调用中使用它。 StackOverflow 社区的支持对我来说总是很方便。
我正在尝试的代码如下。
**Controller**
public class Login_AdminController : ControllerBase
{
[Route("/loginAdmin")]
[HttpPost]
public async Task<string> LoginAdminAsync([FromBody] dynamic content)
{
LoginAdmin L = new LoginAdmin();
var client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:9090");
var request = new HttpRequestMessage(HttpMethod.Post, "/v1/users/login");
var byteArray = new UTF8Encoding().GetBytes($"<{L.username}:{L.df_Password}>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("new_password", "helloWorld123!"));
request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);
Console.WriteLine(response);
return content;
}
}
}
***Model***
public class LoginAdmin
{
public string username = "admin";
public string df_Password = "secret";
public string new_Password { get; set; }
}
谢谢。
【问题讨论】: