سؤال

I took a sample project webapi Self Hosting, the Microsoft page. The webapi starts correctly, but when accessing the address, it gives the error below. I'm using VS2010 and Windows Forms. With Console Applicattion its working, and Windows Forms not working.

Program code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web.Http.SelfHost;
using System.Web.Http;
using System.Net.Http;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        HttpSelfHostServer server;
        HttpSelfHostConfiguration config;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            var config = new HttpSelfHostConfiguration("http://localhost:9090");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:9090");

            //Console.WriteLine("Products in '{0}':", category);

            string query = string.Format("api/products?category={0}", "testes");

            var resp = client.GetAsync(query).Result;
            //resp.EnsureSuccessStatusCode();

            var products = resp.Content.ReadAsAsync<string>().Result;
            MessageBox.Show(products);
        }
    }
}

Controller:

namespace SelfHost
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web.Http;


    public class ProductsController : ApiController
    {

        public string GetProductsByCategory(string category)
        {
            return (category ?? "Vazio");
        }
    }
}

Error:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Object reference not set to an instance of an object.
</ExceptionMessage>
<ExceptionType>System.NullReferenceException</ExceptionType>
<StackTrace>
at System.Web.Http.SelfHost.HttpSelfHostServer.ProcessRequestContext(ChannelContext channelContext, RequestContext requestContext)
</StackTrace>
</Error>
هل كانت مفيدة؟

المحلول

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:

  1. Right after this code server.OpenAsync().Wait(); you call Dispose method on server (because you wrapped everything in using 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.

  2. 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);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top