我在Visual Studio中创建了一个客户端——一个C#控制台应用程序——来使用Restful WebApi类。除了添加、更新、删除一条记录外,我正在尝试显示所有记录,并显示1条记录。我只需要显示"产品"表中的所有记录
在Restful WebApi类中,我使用迁移来为数据库播种。我修改了迁移文件夹中的configuration.cs。在种子方法中添加了以下代码
protected override void Seed(RestfulWebAPIExample.Models.AppDbContext context)
{
context.Products.AddOrUpdate(p => p.ID,
new Product { Name = "Milk", Price = 3.99m, Quantity = 6 },
new Product { Name = "Eggs", Price = 4.99m, Quantity = 12 },
new Product { Name = "Cheese", Price = 6.99m, Quantity = 7 },
new Product { Name = "Bacon", Price = 9.99m, Quantity = 9 }
);
}
我的客户中有产品模型类
namespace RestfulWebAPIExample
{
class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
}
以下是我在客户端的Program.cs中的一些代码,用于显示第一条记录
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace WebAPIExampleClient
{
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}t${1}t{2}", product.Name, product.Price, product.Quantity);
}
}
}
}
}
我在网上找了很长时间,找到了一些网站,但我找不到一个真正好的例子。有人能给我举个例子或给我指明正确的方向吗?我是否以某种方式使用IEnumerable?
这是Restful WebApi类的控制器
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using RestfulWebAPIExample.Models;
namespace RestfulWebAPIExample.Controllers
{
public class ProductsController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET api/Products
public IQueryable<Product> GetProducts()
{
return db.Products;
}
// GET api/Products/5
[ResponseType(typeof(Product))]
public IHttpActionResult GetProduct(int id)
{
Product product = db.Products.Find(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// PUT api/Products/5
public IHttpActionResult PutProduct(int id, Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != product.ID)
{
return BadRequest();
}
db.Entry(product).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST api/Products
[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = product.ID }, product);
}
// DELETE api/Products/5
[ResponseType(typeof(Product))]
public IHttpActionResult DeleteProduct(int id)
{
Product product = db.Products.Find(id);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
db.SaveChanges();
return Ok(product);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProductExists(int id)
{
return db.Products.Count(e => e.ID == id) > 0;
}
}
}
您就快到了,只需做一些小的更改,我认为您的问题就会得到解决。像这样更改GetProducts()
方法:
// GET api/Products
[HttpGet]
[ResponseType(IEnumerable<Product>)]
public IHttpActionResult GetProducts()
{
Ok(return db.Products);
}
请注意,我添加了HttpGet
属性。您不需要就可以做到这一点,但我发现,当您在一个控制器中有多个GET时,指定它会有所帮助。您还应该研究属性路由,因为它会使事情变得更加清晰。
在您的客户端代码中,您这样调用端点:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products");
if (response.IsSuccessStatusCode)
{
IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
}
}
就像我说的,我觉得你们真的很亲密。
希望能有所帮助。