Your code has a bunch of mistakes which I see, and I don't think that I can include them all in commentary. Maybe if you will fix them - this exception will gone.
Issues:
Right after this code
server.OpenAsync().Wait();
you callDispose
method onserver
(because you wrapped everything inusing
statement). This means that when OpenAsync will be finished (and this task will be finished when server is running) - right after this you will close the server.You have a bunch of deadlocks on main thread when you call Wait on the task. Check this article http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx on this.
This is my try to rewrite your example to fix these two issues:
public partial class Form1 : Form
{
HttpSelfHostServer server;
HttpSelfHostConfiguration config;
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
config = new HttpSelfHostConfiguration("http://localhost:9090");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
HttpSelfHostServer server = new HttpSelfHostServer(config);
await server.OpenAsync();
// Server is running: you can show something to user like - it is running
MessageBox.Show("Server is ready!");
}
private async void button2_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:9090");
string query = string.Format("api/products?category={0}", "testes");
var resp = await client.GetAsync(query);
var products = await resp.Content.ReadAsAsync<string>();
MessageBox.Show(products);
}
}