Skip to main content
 首页 » 编程设计

C# API 调用不适用于 HttpWebRequest 但适用于 Postman

2024年02月25日32sky-heaven

我有以下 postman 请求:

这会按预期返回一个 URL:

我正在尝试使用 .Net Core 2.0 应用程序模拟此操作,代码如下:

static void Main(string[] args) 
{ 
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 
 
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://epaper.20minuten.ch/index.cfm/epaper/1.0/getEditionDoc"); 
    httpWebRequest.ContentType = "application/json"; 
    httpWebRequest.Method = "POST"; 
 
    var serializer = new Newtonsoft.Json.JsonSerializer(); 
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
    { 
        using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter)) 
        { 
            serializer.Serialize(tw, 
                new 
                { 
                    editions = new[] 
                    { 
                            new 
                            { 
                                defId = "648", 
                                publicationDate = "2018-03-06" 
                            } 
                    }, 
                    isAttachment = true, 
                    fileName = "Gesamtausgabe_Lausanne_2018-03-06.pdf" 
                }); 
        } 
    } 
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
    { 
        var responseText = streamReader.ReadToEnd(); 
        Console.ReadLine(); 
    } 
} 

但我收到 500 个错误。我错过了什么?

请您参考如下方法:

Postman 可以生成各种各样的代码。要将 RestSharp 与 C# 结合使用,请单击代码按钮/链接并从下拉列表中选择 C# (RestSharp)。

它应该类似于:

有一天我会为 HttpClient 和 HttpWebRequest 贡献一个生成器