2013-06-06 1 views
0

나는 Microsoft 프로젝트 페이지 webapi Self Hosting을 사용했다. webapi가 올바르게 시작되지만 주소에 액세스 할 때 오류가 발생합니다. VS2010 및 Windows Forms를 사용하고 있습니다. 콘솔 응용 프로그램이 작동하고 Windows Forms가 작동하지 않습니다.셀프 호스팅 WebApi C# with WindowsForms 오류

프로그램 코드 :

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> 

답변

2

코드는 내가 보는 실수를 잔뜩 가지고, 나는 생각하지 않습니다 그들 모두를 논평에 포함시킬 수 있습니다. 어쩌면 당신이 그들을 고칠 수 있다면 -이 예외는 사라질 것입니다.

문제 : (당신이 using 문에 모든 것을 감싸 때문에) 당신이 serverDispose 메소드를 호출

  1. 오른쪽이 코드 server.OpenAsync().Wait(); 후. 즉, OpenAsync가 완료되면 (이 작업은 서버가 실행 중일 때 완료됩니다) -이 직후에 서버를 닫습니다.

  2. 작업 대기 중을 호출 할 때 주 스레드에는 많은 교착 상태가 있습니다. 이 문서에서 http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx을 확인하십시오.

이 두 가지 문제를 해결하기 위해 예를 다시 내 시도입니다 :

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); 
    } 
} 
+0

TKS ... 그래서 어떻게됐는데 테스트, 코드가 여전히 쓰레기를 많이 가지고을 ...하지만 당신의 의견을 이해하십시오. 당신이 말한 방식으로 전환했습니다 ... –