C#API调用不';不要使用HttpWebRequest,但要使用Postman

C#API调用不';不要使用HttpWebRequest,但要使用Postman,c#,json,post,httpwebrequest,webrequest,C#,Json,Post,Httpwebrequest,Webrequest,我收到了以下邮递员的请求: 它按预期返回一个URL: 我试图用.Net Core 2.0应用程序模拟此操作,代码如下: static void Main(string[] args) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://epaper.20minut

我收到了以下邮递员的请求:

它按预期返回一个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个错误。我错过了什么?

我想问题可能是因为您正在调用外部url,在某些情况下,它们可能会阻止这样的爬网请求。尝试为请求设置useragent以模拟浏览器调用。

邮递员可以生成多种代码。要将RestSharp与C结合使用,请单击代码按钮/链接,然后从下拉列表中选择
C(RestSharp)

它应该类似于:


有朝一日,我将为HttpClient和HttpWebRequest提供一个生成器

您使用的许多方法在这里并不理想。大多数情况下,您希望使用HttpClient发出Restful请求。另外,请尝试使用
JsonConvert.SerializeObject()
,这通常是我使用的,也是大多数代码示例使用的。
isAttachment
拼写错误。我会运行Fiddler,比较好请求和坏请求的有效负载request@maccettura我愿意接受建议,你会怎么做?@maccettura my bad,我从我的评论中删除了这一点。如果你对使用RestSharp感兴趣,你可以让Postman通过单击“代码”链接并选择
c#(RestSharp)为你生成c#代码
我在下拉列表中添加了“httpWebRequest.UserAgent=”Mozilla/5.0(Windows NT 6.1;Win64;x64)AppleWebKit/537.36(KHTML,像Gecko)Chrome/64.0.3282.186 Safari/537.36”但我还是有同样的问题。为什么它会在postman中工作呢?postman总是像UserAgent一样设置标题,类似于浏览器调用。还可以尝试使用fiddler捕捉邮差呼叫。@J4N刚刚在标题中添加了用户代理,为我工作,谢谢。