WebApi客户端使用Restful WebApi类 - 显示所有记录

时间:2016-04-10 14:57:15

标签: c# asp.net-web-api

我在Visual Studio中创建了一个客户端 - 一个C#控制台应用程序 - 使用Restful WebApi类。我试图获得显示的所有记录,除了获取记录添加,更新,删除和显示1记录。我只需要显示Products表中的所有记录 在我的Restful WebApi类中,我使用迁移来为数据库设定种子。我修改了迁移文件夹中的configuration.cs。在Seed方法

中添加了以下代码
    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;
        }
    }
}

0 个答案:

没有答案