【发布时间】:2018-12-02 08:28:36
【问题描述】:
有一个外部 API,我必须向它发布一些对象以获取一些数据。
我在 Postman 中尝试过,效果很好,如下所示:
我也在用 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 内部服务器错误:
注意:我对其他 API 使用了相同的方式,但不同之处在于将整个对象发送到服务器。
任何人都可以帮助如何将对象应用到内容类型为application/x-www-form-urlencoded的服务器?
【问题讨论】:
-
在 Postman 中,您使用的是 HttpPost 方法,但 C# 代码中使用的是 HttpGet。这是为什么呢?
-
即使在HttpPost同样的问题,也得到了,只是为了在浏览器上测试它
标签: c# asp.net-mvc postman dotnet-httpclient