Search code examples
c#asp.net-corecookiesmodel-view-controllersapb1

How to save authorization values of an API response in MVC Core 3?


I am trying to establish a connection with SAP Business One Service Layer, but when trying to make requests it tells me that I do not have authorization. When you perform in Postman everything goes well.

Login POSTMAN:

enter image description here

Here in the second image, it is seen how a cookie is automatically generated, which I think is what I lack in my MVC Core application.

Get POSTMAN:

enter image description here

When trying to do it in my project, the login if it runs correctly and I get the same answer

Login successful:

enter image description here

But when I do the GET to get the other information I get the following error.

Error GET:

enter image description here

This is my complete code:

enter image description here


Solution

  • A little note for the future: please post your code in actual code blocks and not as images.

    You may consider using the HttpClientHandler to manage cookies for you. This means when you make a request and the response has some Set-Cookie headers, the HttpClientHandler will automatically include those cookies in your next request:

    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");
    }