【问题标题】:Web Api Model is returning null as posting from AngularWeb Api 模型从 Angular 发布时返回 null
【发布时间】:2019-12-03 19:34:21
【问题描述】:

1) Web API 控制器。

    [Route("InsertRecipes")]
        public HttpResponseMessage PostRecipes(Recipes model)
        {
            db.Recipes.Add(recipes);
            db.SaveChanges();
            var message = Request.CreateResponse(HttpStatusCode.Created, model);
            return message;
return CreatedAtRoute("DefaultApi", new { id = recipes.ID }, recipes);
        }

2)Recipes.cs(模型类enter code here

[Table("tbl_Recipes")]
public class Recipes
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string ImagePath { get; set; }
    public Ingredients Ingredients;

}

3) 在 Angular 中调用 POST 方法

storeRecipes(){
        const recipes = this.recipeService.getRecipes();
        this.http.post('http://localhost:62286/Api/Recipes/InsertRecipes',recipes).pipe()
                .subscribe(response =>{
                    console.log(response);
                });
    }

4) 这是从 Angular 接收的 JSON

 {
    "name": "Fish Curry",
    "description": "Fish Curry - taste really awesome",
    "imagePath": "https://ichef.bbci.co.uk/food/ic/food_16x9_1600/recipes/fish_curry_09718_16x9.jpg",
    "ingredients": [
      {
        "name": "Green Chilli",
        "amount": 5
      },
      {
        "name": "Fish",
        "amount": 1
      },
      {
        "name": "Ginger Galic Paste",
        "amount": 1
      },
      {
        "name": "Onion",
        "amount": 2
      },
      {
        "name": "Tomato",
        "amount": 2
      },
      {
        "name": "Master",
        "amount": 3
      },
      {
        "name": "Masala",
        "amount": 2
      }
    ]
  }

在从 angular 发布时,我一直在该控制器的模型中收到 null。

【问题讨论】:

  • 你在哪里看到空值? recipeService.getRecipes() 是否返回上面 4) 中列出的 JSON?您在 console.log(response) 中看到 null 了吗?
  • 没有在 web Api 模型"public HttpResponseMessage PostRecipes(Recipes 模型)"

标签: asp.net angular asp.net-web-api json.net webapi


【解决方案1】:

您应该使用FromBody[HttpPost]。您将模型(这里是食谱)放在您的 http 请求的正文中,这就是您应该从 body 接收它的原因。

在 web api 中修改您的 PostRecipes,如下所示:

  [Route("InsertRecipes")]
  [HttpPost]
        public HttpResponseMessage PostRecipes([FromBody]Recipes model)
        {
            db.Recipes.Add(recipes);
            db.SaveChanges();
            var message = Request.CreateResponse(HttpStatusCode.Created, model);
            return message;
return CreatedAtRoute("DefaultApi", new { id = recipes.ID }, recipes);
        }

然后在您的角度服务中:

public storeRecipes() {
    // make sure that recipes is not null ....
    const recipes = this.recipeService.getRecipes();
    this.http.post('http://localhost:62286/Api/Recipes/InsertRecipes', recipes, this.setHttpHeader()).pipe()
        .subscribe(response => {
            console.log(response);
        });
}
private setHttpHeader() {
    const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
    let options = { headers: headers };
    return options;
}

【讨论】:

  • 那么我在模型中也得到了空值。请找到从不同服务获取食谱的代码
  • getRecipes(){ return this.recipes.slice(); }
  • 你确定const recipes = this.recipeService.getRecipes();中有数据
  • 私人食谱:Recipe[]= [ new Recipe('Fish Curry', 'Fish Curry - 味道真棒', 'ichef.bbci.co.uk/food/ic/food_16x9_1600/recipes/…', [ new Ingredient ('Green Chilli', 5) , 新成分 ('Fish',1), 新成分 ('Ginger Galic Paste',1), 新成分 ('Onion',2), 新成分 ('Tomato',2), 新成分 ('Master', 3), .... ]) ];
  • 我通过 getRecipes(){ 返回 this.recipes.slice(); }
【解决方案2】:

您错过了[HttpPost][FromBody],请按以下方式操作:

[HttpPost]
[Route("InsertRecipes")]
        public HttpResponseMessage PostRecipes([FromBody] Recipes model)
        {
            db.Recipes.Add(recipes);
            db.SaveChanges();
            var message = Request.CreateResponse(HttpStatusCode.Created, model);
            return message;
return CreatedAtRoute("DefaultApi", new { id = recipes.ID }, recipes);
        }

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2020-10-21
    • 2020-10-20
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多