403在C#中使用Webrequest的禁止错误,但在邮递员中有效

时间:2018-03-31 14:50:33

标签: c# curl asp.net-web-api postman

我有一个授权代码,在调用api时我需要在body中传递一些标头值。当从邮递员那里尝试相同时它的工作正常,但C#Webclient抛出403错误。

以下代码: -

public string GetResponse(string AuthCode)         {

string url = "https://example.com//openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa";
        Uri uri = new Uri(string.Format(url));

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = "code=" + AuthCode + "&redirect_uri=" + "http://localhost:8080";
        byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(postData);

        // Create the request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        httpWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " +  "MzE4OGQwYjQtZTRlOC00MTZjLTg5NjAtZDNlYWFhMmNjY2IxOkx3NiVBa0x4NWtPM01rJTJ5RWwxbW1jR0ZYZmhTQmk1NHhIRCpzNiUyVUd5WXN0MCNVbyNMNWQhcVlpZE93djc=");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.ContentLength = data.Length;
        httpWebRequest.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";

        Stream stream = httpWebRequest.GetRequestStream();
        stream.Write(data, 0, data.Length);
        stream.Close();

        // Get the response
        HttpWebResponse httpResponse = null;
        try
        {
            httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception while getting resource " + ex.Message);
            return null;
        }

        string result = null;
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }

        return result;

}

Postman Curl命令: -

从卷曲请求生成:

curl -X POST ' https://example.com//openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa' -H'授权:基本MzE4OGQwYjQtZTRlOC00MTZjLTg5NjAtZDNlYWFhMmNjY2IxOkx3NiVBa0x4NWtPM01rJTJ5RWwxbW1jR0ZYZmhTQmk1NHhIRCpzNiUyVUd5WXN0MCNVbyNMNWQhcVlpZE93djc =' -H'缓存控制:无缓存' -H'内容类型:application / x-www-form-urlencoded' -d'代码= 93317468-7464-4804-b38a-43e13265c4ac& redirect_uri = http%3A%2F%2Flocalhost%3A8080%2F'

我无法弄清楚这个问题。任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

使用RestSharp解决问题并传递正确的标头值

parse_requirements