pedroremedios
pedroremedios

Reputation: 801

C# GetAsync Won't Work with Django Rest Framework

This is the function in my HomeController.cs:

async Task<Dictionary<Object, Object>> GetSiteWithID(int ID)
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "94afa9a8b0804e65a53d335dec230478f69b39c5");
            HttpResponseMessage responseMessage = await client.GetAsync("http://localhost:8000/site/1");
            responseMessage.EnsureSuccessStatusCode();
            return await responseMessage.Content.ReadAsAsync<Dictionary<Object, Object>>();
        }
    }

The problem is it's sending the header as "Authorization: Token 94afa9a8b0804e65a53d335dec230478f69b39c5" correctly but Django Rest Framework doesn't get it.

Anything else I need to send because if I test with Postman, it works but it is also sending other stuff which I don't know if it's necessary.

UPDATE: Yes I am using localhost:8000 - The default port for the dev server in django. I will be moving to a production server after. The response I'm getting from the django server is 'Authentication details were not provided'. Status code 401 - Unauthorized.

UPDATE: Tried with react and after implementing a CORS whitelist list in Django, the request worked! When I added the .NET local server to the whitelist, Django still said that the 'Authentication details were not provided'. So something in .Net Core 2.2 is not sending the headers!

Upvotes: 1

Views: 624

Answers (1)

pedroremedios
pedroremedios

Reputation: 801

It's solved. Apparently the Django server was returning a 301 because of no trailing slash and my code was not taking that into account. If I test the url without the trailing slash in postman, it handles the 301 and resends the request with the trailing slash to what I can gather. Putting a trailing slash on the url bypasses that 301 response.

Upvotes: 1

Related Questions