我正在尝试学习如何创建Web Api,但我有一个错误。
我不知道该怎么办,首先当我使用它时需要使用后缀M,VS显示错误:
不能将"RESTfullApi.Models.Product []"隐式转换为 "RESTfullApi.Models.Product">
我试图在互联网上找到答案,但没有任何解释这种情况。也许你知道它有什么问题?
这是我练习的教程:https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
产品控制器.cs
using RESTfullApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RESTfullApi.Controllers
{
public class ProductsController : ApiController
{
Product products = new Product[]
{
new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
}
}
产品.cs(型号(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RESTfullApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
消息是不言自明的。将products
更改为
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};