如何在 MVC Core 3 中保存 API 响应的授权值?
How to save authorization values of an API response in MVC Core 3?
我正在尝试与 SAP Business One Service Layer 建立连接,但在尝试发出请求时它告诉我我没有授权。
当你在 Postman 中表演时一切顺利。
登录邮递员:
在第二张图片中,可以看到cookie是如何自动生成的,我认为这是我的MVC Core应用程序所缺少的。
获取邮递员:
在我的项目中尝试执行此操作时,登录是否正确运行并且我得到相同的答案
登录成功:
但是当我执行 GET 获取其他信息时,出现以下错误。
获取错误:
这是我的完整代码:
未来的一点注意事项:请post您的代码在实际代码块中而不是图像中。
您可以考虑使用 HttpClientHandler to manage cookies for you. This means when you make a request and the response has some Set-Cookie headers,HttpClientHandler 将在您的下一个请求中自动包含这些 cookie:
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
var jsonString = @"{""CompanyDB"":""MICOMPANY""}";
var postData = new StringContent(jsonString, Encoding.UTF8, "application/json");
var loginResponse = await client.PostAsync("https://some-site.com/loginPath", postData);
// ...
// This GET request will automatically include the cookies you received above
var dataResponse = await client.GetAsync("https://some-site.com/give/me/data");
}
我正在尝试与 SAP Business One Service Layer 建立连接,但在尝试发出请求时它告诉我我没有授权。 当你在 Postman 中表演时一切顺利。
登录邮递员:
在第二张图片中,可以看到cookie是如何自动生成的,我认为这是我的MVC Core应用程序所缺少的。
获取邮递员:
在我的项目中尝试执行此操作时,登录是否正确运行并且我得到相同的答案
登录成功:
但是当我执行 GET 获取其他信息时,出现以下错误。
获取错误:
这是我的完整代码:
未来的一点注意事项:请post您的代码在实际代码块中而不是图像中。
您可以考虑使用 HttpClientHandler to manage cookies for you. This means when you make a request and the response has some Set-Cookie headers,HttpClientHandler 将在您的下一个请求中自动包含这些 cookie:
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
var jsonString = @"{""CompanyDB"":""MICOMPANY""}";
var postData = new StringContent(jsonString, Encoding.UTF8, "application/json");
var loginResponse = await client.PostAsync("https://some-site.com/loginPath", postData);
// ...
// This GET request will automatically include the cookies you received above
var dataResponse = await client.GetAsync("https://some-site.com/give/me/data");
}