【问题标题】:Passing variables to IHttpActionResult Methods将变量传递给 IHttpActionResult 方法
【发布时间】: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


    【解决方案1】:

    如果你想 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 代码,以便它发送复杂的对象。

    【讨论】:

    • 我首先使用 EF 数据库,所以我已经是 Product.cs 类,其中定义了名称、价格和描述。如果我添加另一个类 MyRequest 使用你建议的变量名,我有点迷茫.我应该像这里一样关注docs.microsoft.com/en-us/aspnet/web-api/overview/…
    • 是的。或者您可以重用现有的产品模型
    • 如果是较小的项目,我会重用相同的模型,否则我会创建特殊的 RequestDTO 对象。在我看来,这是最佳实践,因为您可以发送其他的,而不仅仅是 Product。
    猜你喜欢
    • 1970-01-01
    • 2016-04-20
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多