我拿了一个示例项目 webapi Self Hosting,Microsoft 页面。webapi正常启动,但访问地址时,报如下错误。我正在使用 VS2010 和 Windows 窗体。使用控制台应用程序,它的工作,而 Windows 窗体不工作。
程序代码:
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);
}
}
}
控制器:
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");
}
}
}
错误:
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>