【发布时间】:2017-05-15 01:57:05
【问题描述】:
我正在尝试学习如何创建 Web Api,但我遇到了一个错误。
我不知道该怎么办,首先我使用它时需要使用后缀M,VS显示错误:
您不能将“RESTfullApi.Models.Product []”隐式转换为 "RESTfullApi.Models.Product"
我试图在互联网上找到答案,但没有解释这个案例。 也许你知道它有什么问题?
ProductsController.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;
}
}
}
Product.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; }
}
}
【问题讨论】:
-
Product products = new Product[]你是说你有一个名为products类型为Product的变量——产品的单个实例,你给它分配了一个产品数组——类型不匹配。将变量类型更改为Product[]。或者您可以简单地使用var进行声明,这样可以省去您将来的一些思考(var products = new Product[] {)
标签: c# asp.net-mvc asp.net-web-api