将变量传递给IHttpActionResult方法

时间:2017-07-25 13:49:07

标签: android asp.net-web-api entity-framework-6 jsonhttpclient

我想在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测试我的api for POST时,我获得了405状态代码。我尝试过使用:

    //[Route("api/products/{name}/{price}/{description}")]
    // POST: api/Products
    [HttpPost]
    //[ResponseType(typeof(Product))]
    public IHttpActionResult PostProduct(string name, decimal price, string description)
    {

以及示例im(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
        };

1 个答案:

答案 0 :(得分:0)

如果你想POST到MVC控制器,我会这样做:

使用您的属性创建复杂模型(类):

class MyRequest{

public string name {get;set};
public  decimal price{get;set};

public  string description{get;set};
}

并按照以下方式更改您的控制器:

  public Product Post(MyRequest request)

不要忘记更改您的Android代码,以便它发送复杂的对象。