Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET Web API未获取新发布的项目_C#_Asp.net_Wpf_Asp.net Web Api_Owin - Fatal编程技术网

C# ASP.NET Web API未获取新发布的项目

C# ASP.NET Web API未获取新发布的项目,c#,asp.net,wpf,asp.net-web-api,owin,C#,Asp.net,Wpf,Asp.net Web Api,Owin,我正在学习ASP.NET Web API是如何工作的,因为我正在从事的项目需要它。我正在使用OWIN在WPF应用程序中托管Web API 我很难让我的POST方法发挥作用。当我发布一个新产品时,它会被添加到产品列表中,但当我尝试获取所有产品时,它不会显示 这是我用来测试它的一个类: class Program { const string baseAddress = "http://localhost:9000/"; static void Main(s

我正在学习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");
                }
            }
        }
    }

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


为您的
列表使用持久存储

您的控制器构造函数是否会为每个请求调用?@Brendan是的,每个请求都会调用构造函数,这在您提到它时是有意义的。我改变了初始化列表的方式,现在它可以工作了。谢谢
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");
        }
    }
[{"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}]