【问题标题】:C# POST request works on POSTMAN but not on C# HttpWebRequestC# POST 请求适用于 POSTMAN,但不适用于 C# HttpWebRequest
【发布时间】:2019-12-27 16:36:57
【问题描述】:

我只在 C# 中得到代码 400,而当我使用邮递员时,我得到 200! 它具有相同的属性。

我最初将这些类创建为 JSONProperty 属性,但在分散后仍然得到代码 400。

在提琴手内发现异常 - message=parameters:“XXXXX.AzureAd.XXX.Types.NewDescriptionEntry”类型上不存在属性“Changedby”。确保仅使用类型定义的属性名称。

创建类后C#调试模式下的JSON——JSON模式。

 // Serialize our concrete class into a JSON String
                var stringPayload = await Task.Run(() => 

JsonConvert.SerializeObject(payload_transferIncident));

            // build the URL we'll hit
            var url = string.Format("https://XXXXXX", "YYYYY", id, "XXXX");

            //create the request
           var req = HttpWebRequest.CreateHttp(url);

            //add in the cert we'll authenticate with
             req.ClientCertificates.Add(IcmIncidentOperation.GetCert("XXXXXX"));

            req.ContentType = "application/json";
            req.Method = "POST";
            if (req == null)
                throw new ApplicationException(string.Format("Could not create the httprequest from the url:{0}", url));
            try
            {
                using (var streamWriter =   new StreamWriter(req.GetRequestStream()))
                {
                    streamWriter.Write(stringPayload);
                }
                var httpResponse = (HttpWebResponse)req.GetResponse();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                var httpResponse = (HttpWebResponse)req.GetResponse();
            }

【问题讨论】:

  • 我鼓励您调试此代码,您会立即看到您没有向请求流写入任何内容。您打算将payload_transferIncident 的序列化结果写入其中,但您的代码并未将其分配给任何变量,它只是将其丢弃。

标签: c# http post httpwebrequest


【解决方案1】:

使用 HttpRequest POST METHOD 尝试这种方式

try
        {
            var baseAddress = new Uri("Your base url");

            using (var httpClient = new HttpClient
            {
                BaseAddress = baseAddress
            })
            {
                var json =Newtonsoft.Json.JsonConvert.SerializeObject( payload);

                using (var content = new StringContent( json, System.Text.Encoding.Default, "application/json"))
                {
                    try
                    {
                        using (var response = await httpClient.PostAsync("end-point url method", content))
                        {

                            result = await response.Content.ReadAsStringAsync();
                        }
                    }
                    catch(Exception ex)
                    {
                        return ex.Message;
                    }

                }
            }

        }
        catch (Exception ex)
        {
            result = ex.Message;
        }

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2017-08-06
    • 1970-01-01
    • 2020-06-17
    • 2018-06-22
    • 2018-08-27
    • 1970-01-01
    • 2018-03-25
    • 2015-09-19
    相关资源
    最近更新 更多