找不到类型或名称空间'frombody'

时间:2017-08-31 03:58:19

标签: c# asp.net rest api

我遇到与formbody相关的错误。我在CRUD REST API中创建dot net。以下是代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using ProductDataAccess;

public ProductEntities Entities = new ProductEntities();

 public HttpResponseMessage Post([FormBody] Product product)
    {
        try
        {
            Entities.Products.Add(product);
            Entities.SaveChanges();
            var response = Request.CreateResponse(HttpStatusCode.Created, product);
            response.Headers.Location = Request.RequestUri;

            return response;
        }
         catch (Exception)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data Not Inserted");

        }
    }

更新1

ProductDataAccess文件作为新项目创建,但两者都在同一解决方案下。控制器的代码在

之下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using ProductDataAccess;

namespace REST_API.Controllers
{
   public class ProductsController : ApiController
   {
    public ProductEntities Entities = new ProductEntities();

    public HttpResponseMessage Get()
    {
        try
        {
            return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.ToList());
        }
        catch
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data Found");
        }
    }

    public HttpResponseMessage Get (int id)
    {
        try
        {
            return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.SingleOrDefault(p => p.Id == id));
        }
        catch
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data Found");
        }
    }

    public HttpResponseMessage Post([FormBody] Product product)
    {
        try
        {
            Entities.Products.Add(product);
            Entities.SaveChanges();
            var response = Request.CreateResponse(HttpStatusCode.Created, product);
            response.Headers.Location = Request.RequestUri;

            return response;
        }
         catch (Exception)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data Not Inserted");

        }
    }
}}

我在这里收到formbody错误。我得到一个问题answer,但仍然无法得到理想的结果。

任何帮助都将受到高度赞赏

2 个答案:

答案 0 :(得分:1)

FormBody 必须是 FromBody 操作过滤器让方法知道必须使用请求中的数据填充变量对象。

对API的POST请求正文中的示例JSON对象:

{
  "Name" : "Product Name",
  "Price" : 0.50 
}

获取请求主体并解析为C#对象的API方法:

public HttpResponseMessage Post([FromBody] Product product)
{
   var name = product.Name; // "Product Name"
   var price = product.Price: // 0.50
}

干杯!

答案 1 :(得分:0)

导入以下名称空间:

using System.Web.Http;

如果您使用的是dot-net-core,请导入以下内容

using Microsoft.AspNetCore.Mvc;