【发布时间】:2017-07-25 13:49:06
【问题描述】:
我想在 android 中使用 WebApi,如下所示(在 NewProductActivity.java 中):
protected String doInBackground(String... params) {
List<NameValuePair> args = new ArrayList<NameValuePair>();
args.add(new BasicNameValuePair("name", editTextName.getText().toString()));
args.add(new BasicNameValuePair("price", editTextPrice.getText().toString()));
args.add(new BasicNameValuePair("description", editTextDescription.getText().toString()));
JSONHttpClient jsonHttpClient = new JSONHttpClient();
Product product = (Product) jsonHttpClient.PostParams(ServiceUrl.PRODUCT, args, Product.class);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
return null;
}
在我的 Web api 中,我将变量分配给 ProductsController.cs 中的参数,如下所示:
[HttpPost]
//[ResponseType(typeof(Product))]
public IHttpActionResult InsertProduct(string name, decimal price, string description)
{
Product product = new Product()
{
Name = name,
Price = price,
Description = description
};
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
db.SaveChangesAsync();
return Ok(product.ID);
}
当我在 Fiddler 中为 POST 测试我的 api 时,我得到一个 405 状态码。我尝试过使用:
//[Route("api/products/{name}/{price}/{description}")]
// POST: api/Products
[HttpPost]
//[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct(string name, decimal price, string description)
{
以及下面示例中的原始实现 (http://hintdesk.com/how-to-call-asp-net-web-api-service-from-android),但我仍然得到 405:
[HttpPost]
//[ResponseType(typeof(Product))]
public Product Post(string name, decimal price, string description)
{
Product product = new Product()
{
Name = name,
Price = price,
Description = description
};
【问题讨论】:
标签: android asp.net-web-api entity-framework-6 jsonhttpclient