HTTP POST请求在Postman中有效,但在代码中无效

时间:2018-12-02 08:28:36

标签: c# asp.net-mvc postman dotnet-httpclient

有一个外部API,我必须向其发布一些对象以获取一些数据。

我在Postman中进行了尝试,如下所示,效果很好:

enter image description here

我也在用C#编写的ASP.NET MVC应用程序中尝试过:

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); 
    }
}

我收到HTTP 500内部服务器错误:

enter image description here

注意:我对另一种API使用了相同的方法,但这种方法的不同之处在于将整个对象发送到服务器。

任何人都可以帮助如何将内容类型为application/x-www-form-urlencoded的对象应用于服务器?

2 个答案:

答案 0 :(得分:3)

在邮递员图像中,您正在发布表单数据并获得json响应。

在C#代码中,您调用PostAsJsonAsync,它将发送JSON内容类型。

使用FormUrlEncodedContent并在其中填充要发送的数据。

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); 

答案 1 :(得分:0)

我的答案的解决方案是

     [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);
    }

以及执行发布请求的方法:

    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;

    }