Postman和HttpWebRequest给出不同的结果

问题描述

我是C#的新手,我想将JSON请求发送到API并获取JSON响应作为回报,以便可以在我的应用程序中使用它。但是,每次我提出请求时,我都会收到404错误。当我使用相同的POST数据执行Postman Request时,我得到了肯定的结果。

下面是我使用邮递员发送给API的JSON。

{
  "ActionId": null,"AgentCode": "MerchantCode:Password","Mpin": null,"Amount": 0.0,"CustomerMSISDN": null,"ServiceId": 0,"MTI": "0300","TerminalId": null,"TransactionRef": null,"CustomerAccount": null,"CustomerData": null,"Product": null,"ServiceProvider": "Yomoney","Source": null,"PaymentMethod": null,"ProcessingCode": "420000","Quantity": null,"OrderLines": null,"Narrative": null,"Note": null,"MaxSale": 0.0,"MinSale": 0.0,"TransactionType": 2
}

这是我要发送到的URL:

https://www.yomoneyservice.com/yoclient/transaction 

这是我得到的答复

{"ResponseCode":"00000","Description":null,"Balance":null,"TransactionCode":null,"vouchers":null,"AgentCode":null,"Mpin":null,"Amount":0,"MaxSale":0,"MinSale":0,"CustomerMSISDN":null,"ServiceId":0,"MTI":null,"TerminalId":null,"TransactionRef":null,"TransactionType":0,"CustomerAccount":null,"CustomerData":null,"Product":null,"Quantity":0,"Action":null,"ProcessingCode":null,"Note":"Purchase","Narrative":"[{\"Id\":\"1\",\"Name\":\"THE
REDEEMED
SOLDIER\",\"Value\":\"12\",\"Note\":\"supplier\",\"Image\":null,\"Description\":null,\"Section\":null,\"ServiceId\":12,\"Currency\":null,\"ActionId\":1,\"TransactionType\":0,\"supplierId\":null,\"Amount\":null,\"Count\":0,\"date\":\"0001-01-01T00:00:00\",\"WebLink\":null,\"HasProducts\":false,\"IsAdvert\":false,\"IsNotAdvert\":false,\"IsShare\":false,\"RequireVerification\":false,\"RequiresRegistration\":false,\"RequiresAmount\":false},{\"Id\":\"1\",\"Name\":\"BUY
VOUCHER\",\"Value\":\"10\",\"Image\":\"~/Content/logos/YOMONEY/yomoney_v_logo.png\",\"ServiceId\":10,\"Name\":\"ECONET
PINLLESS\",\"Value\":\"8\",\"Image\":\"~/Content/logos/YOMONEY/buddie.png\",\"ServiceId\":8,\"Name\":\"TELECEL
PINLESS\",\"Value\":\"3\",\"ServiceId\":3,\"Name\":\"Econet\",\"Value\":\"2\",\"ServiceId\":2,\"HasProducts\":true,\"Name\":\"NetoNE
PINLESS\",\"Value\":\"1\",\"ServiceId\":1,\"RequiresAmount\":false}]"}

现在,在C#中,我正在使用WebRequest&WebResponse,但出现404错误提示“远程服务器返回错误:(404)未找到。”。下面是我的C#代码

try
            {
                string url = String.Format("https://www.yomoneyservice.com/yoclient/transaction");
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";                        
                
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(yomoneyRequest,Formatting.Indented);

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                        yomoneyResponse = JsonConvert.DeserializeObject<YomoneyResponse>(result);
                    }
                }                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

我不确定在C#代码中哪里出了错,有人可以帮助我吗?

解决方法

我试图在代码和邮递员中重现您的用例。您的观察是正确的,它适用于邮递员,但不适用于C#代码。

然后,我观察到从代码和邮递员发送的请求之间的区别。区别在于cookie。

邮递员发送一个名为“ AspxAutoDetectCookieSupport”的cookie,其值为“ 1”。

然后我修改了您的代码,以便在向API发送请求时也添加cookie,并且效果很好。

要将cookie添加到HttpWebRequest,您需要使用CookieContainer

您需要初始化httpWebRequest的CookiContainer属性并向其中添加cookie。

您需要按以下方式更改代码。

try
{

    string url = String.Format("https://www.yomoneyservice.com/yoclient/transaction");
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST"; 
    httpWebRequest.CookieContainer = new CookieContainer();
    Cookie c = new Cookie("AspxAutoDetectCookieSupport","1");
    c.Domain = "www.yomoneyservice.com";
    httpWebRequest.CookieContainer.Add(c);  
    string json = JsonConvert.SerializeObject(yomoneyRequest,Formatting.Indented);
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        streamWriter.Write(json);
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        var yomoneyResponse = JsonConvert.DeserializeObject<YomoneyResponse>(result);
    } 
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
}

我希望这可以帮助您解决问题。