Saif Obeidat
Saif Obeidat

Reputation: 148

HTTP POST request works in Postman but doesn't work in code

There's an external API, and I have to post some objects to it to get some data.

I tried it in Postman, and it works fine as you see below:

enter image description here

And I tried it in my ASP.NET MVC application written in C# as well:

public class TestingController : SurfaceController
{
    [System.Web.Http.HttpGet]
    public async System.Threading.Tasks.Task<ActionResult> Hit()
    {
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        Order order = new Order();
        ClientDetailsModel ClientDetails = new ClientDetailsModel();
        ProductDetailsModel ProductDetails = new ProductDetailsModel();
        ShippingAdressModel ShippingAdress = new ShippingAdressModel();

        ClientDetails.ClientName = "x";
        ClientDetails.Email = "x";
        ClientDetails.Note = "x";
        ClientDetails.Tel = "x";

        ProductDetails.ColorID = "1";
        ProductDetails.Quantity = "1";
        ProductDetails.SizeID = "1";
        ProductDetails.ProductMatrixRecordID = "1";

        ShippingAdress.City = "x";
        ShippingAdress.CountryID = "1";
        ShippingAdress.PostalAddress = "x";
        ShippingAdress.Street = "x";
        ShippingAdress.StreetAddress = "x";

        order.ResponseType = "JSON";
        order.Token = "P74kXRjM4W44l9qNw8u3";
        order.PaymentMode = "1";
        order.ProductDetails = ProductDetails;
        order.ShippingAddress = ShippingAdress;
        order.ClientDetails = ClientDetails;
        order.CurrencyAbbreviation = "JOD";

        var response = await client.PostAsJsonAsync<Order>("https://bmswebservices.itmam.com/OrderingManagement/Orders.asmx/PlaceOrder", order);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine("ERROR:  Products Not Posted." + response.ReasonPhrase);
            return null;
        }

        var cs = await response.Content.ReadAsAsync<Order>();

        return Json(cs); 
    }
}

I got HTTP 500 internal server error:

enter image description here

Note: I used the same way for another APIs but the difference in for this one is sending entire objects to the server.

Anyone can help in how to apply objects to server with the content-type application/x-www-form-urlencoded?

Upvotes: 4

Views: 13057

Answers (2)

Saif Obeidat
Saif Obeidat

Reputation: 148

the solution of my answer was

     [System.Web.Http.HttpPost]
    public ActionResult PlaceOrder(ClientDetailsModel ClientDetails, List<ProductDetailsModel> ProductDetails, ShippingAddressModel ShippingAddress, string PaymentMode, string CurrencyAbbreviation,string OrderPageURL)
    {
        HttpClient client = new HttpClient();
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var systemToken = Session["SysToken"].ToString();
        var url = Session["DomainURL"]+"/OrderingManagement/Orders.asmx/PlaceOrder";
        var parameters = "ResponseType=JSON";
        parameters += "&Token=" + systemToken;
        parameters += "&PaymentMode=" + PaymentMode;
        parameters += "&ProductDetails=" + JsonConvert.SerializeObject(ProductDetails);
        parameters += "&ShippingAddress=" + JsonConvert.SerializeObject(ShippingAddress);
        parameters += "&ClientDetails=" + JsonConvert.SerializeObject(ClientDetails);
        parameters += "&CurrencyAbbreviation=" + CurrencyAbbreviation;
        parameters += "&OrderPageURL="+ websiteDomain+"/en/order-details/?comingfrom=email";
        var response = Functions.PostRequest(url, parameters);
        var res = JsonConvert.DeserializeObject(response);
        Session["OrderNo"] = res.No;
        Session["AuthenticationCode"] = res.AuthenticationCode;
        return Json(response);
    }

and the method that does the post request :

    static public dynamic PostRequest(string apilink, string parameters)
    {
        WebRequest request = WebRequest.Create(apilink);
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        string postData = parameters;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.

        WebResponse response = request.GetResponse();


        // Display the status.

        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.

        // Clean up the streams.
        //  var decodedJsonString = Json.Decode(responseFromServer);

        // return decodedJsonString; 
        return responseFromServer;

    }

Upvotes: 0

Nkosi
Nkosi

Reputation: 247088

In postman image you are posting form data and getting json response.

In the c# code you call PostAsJsonAsync which will send JSON content type.

Use FormUrlEncodedContent and populate it with the data to send.

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

//...code omitted for brevity

var order = new Dictionary<string, string>();

order["ResponseType"] = "JSON";
order["Token"] = "P74kXRjM4W44l9qNw8u3";
order["PaymentMode"] = "1";
order["ProductDetails"] = JsonConvert.SerializeObject(ProductDetails);
order["ShippingAddress"] = JsonConvert.SerializeObject(ShippingAdress);
order["ClientDetails"] = JsonConvert.SerializeObject(ClientDetails);
order["CurrencyAbbreviation"] = "JOD";

var content = new FormUrlEncodedContent(order);

var url = "https://bmswebservices.itmam.com/OrderingManagement/Orders.asmx/PlaceOrder";
var response = await client.PostAsync(url, content);    
if (!response.IsSuccessStatusCode) {
    Console.WriteLine("ERROR:  Products Not Posted." + response.ReasonPhrase);
    return null;
}

var cs = await response.Content.ReadAsAsync<Order>();

return Json(cs); 

Upvotes: 5

Related Questions