繁体   English   中英

ASP.NET Web API没有获得新发布的项目

[英]ASP.NET Web API not getting newly posted item

我正在学习ASP.NET Web API的工作方式,因为我正在从事的项目需要它。 我正在使用OWIN在WPF应用程序中托管Web API。

我无法使POST方法生效。 当我发布新产品时,它将被添加到产品列表中,但是当我尝试获取所有产品时,它不会显示。

这是我用来测试的课程:

class Program
    {
        const string baseAddress = "http://localhost:9000/";

        static void Main(string[] args)
        {


            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                RunAsync().Wait();
            }

            Console.ReadLine();
        }

        static async Task RunAsync()
        {
            using(var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseAddress);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //GET initial products
                HttpResponseMessage response = await client.GetAsync("api/products/");
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine(await response.Content.ReadAsStringAsync() + "\n");
                }

                //POST new product
                Product gizmo = new Product() { Id = 4, Name = "Gizmo", Price = 50, Category = "Widget"};
                try
                {
                    response = await client.PostAsJsonAsync("api/products", gizmo);
                    response.EnsureSuccessStatusCode();
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine(e.Message);
                }

                //GET all products (should contain gizmo product)
                response = await client.GetAsync("api/products/");
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine(await response.Content.ReadAsStringAsync() + "\n");
                }
            }
        }
    }

这是我的Controller类:

public class ProductsController : ApiController
    {
        List<Product> products = new List<Product>();

        public ProductsController()
        {
            products.Add(new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 });
            products.Add(new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M });
            products.Add(new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M });
        }

        public IEnumerable<Product> Get()
        {
            return products;
        }

        public IHttpActionResult Get(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        public void Post(Product product) {
            products.Add(product);
            Console.WriteLine("Product Added: " + products[products.Count - 1].Name + "\n");
        }
    }

输出显示新的Gizmo项目已添加到列表中:

[{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

Product Added: Gizmo

[{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

您的控制器构造函数可能会为每个请求调用(请记住,HTTP是无状态的)。

为您的List<Product>使用永久性存储。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM