0

I am trying to invoke a rest api. But I get 401 unauthorized. The same call works fine from C# and postman with the same token.

Here is a snippet of the code I am using:

$contentType = "application/json" 
try 
{   
    $response = Invoke-RestMethod -Uri $URL -Method Post -Headers @{Cookie = "token=xxxxxx"} -ContentType $contentType -Body $json    
    return $response.StatusCode
}
catch 
{         
    Write-Host "Error: $($_.Exception.Message)"         
    return $null     
}

This is the C# code that is working:

HttpWebRequest webRequest;
        HttpWebResponse response;
        string URL ="https://apiurl/method";
        string header ="Cookie";
        string token ="token=xxxxxx";
 
        webRequest = (HttpWebRequest)WebRequest.Create(URL);
        webRequest.Headers.Add(header, token);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json";
        using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
             var attributes= new RestAttributes();
             string json = new JavaScriptSerializer().Serialize(attributes);
             streamWriter.Write(json);
        }
        response = (HttpWebResponse)webRequest.GetResponse();
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(streamResponse);
        string Response = streamReader.ReadToEnd();
        return response.StatusCode.ToString();

Tried encoding the token, also tried Invoke-WebRequest. Nothing works.

6
  • The code you've posted is incomplete, can't have a try block without finally block or at least 1 catch block. Commented Mar 27, 2024 at 14:56
  • Cookie = "Token=XXXXX" This doesnt seem like a header but like this needs to be a cookie. Is that correct? Commented Mar 27, 2024 at 15:08
  • It is a header, it’s just named that way. In postman I send the same header. Header key is Cookie and the value is token=xxxxxx Commented Mar 27, 2024 at 15:24
  • @MathiasR.Jessen Added the catch block Commented Mar 27, 2024 at 15:28
  • Can you include the code that generates "xxxxxx" and the relevant C# code as well? Commented Mar 27, 2024 at 15:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.