2012-11-03 50 views
6

我有一個默認的mvc web api實例,它是從Visual Studio 2012模板構建的。它在默認的ValuesController中具有以下路由和post方法 - 除了Post方法的內容之外,MVC網站未經初始創建修改。另外,我正在使用.NET Framework 4.0,因爲我打算針對Azure。控制檯應用程序HttpClient發佈到mvc web api

註冊方法

public static void Register(HttpConfiguration config) 
{ 
    config.Routes.MapHttpRoute(
     name: "DefaultApi", 
     routeTemplate: "api/{controller}/{id}", 
     defaults: new { id = RouteParameter.Optional } 
    ); 
} 

和Post方法

// POST api/values 
    public string Post([FromBody]string value) 
    { 
     if (value != null) 
     { 
      return "Post was successful"; 
     } 
     else 
      return "invalid post, value was null"; 
    } 

我創建了使用HttpClient的模擬發佈到服務控制檯應用程序,但不幸的是,「價值」進來的帖子是始終爲空。 Post方法在HttpClient上的PostAsync調用之後被成功命中。

這不是我清楚如何映射我的要求,使得值包含我傳入的StringContent ...

static void Main(string[] args) 
    { 
     string appendUrl = string.Format("api/values"); 
     string totalUrl = "http://localhost:51744/api/values"; 
     HttpClient client = new HttpClient(); 
     client.DefaultRequestHeaders.Add("Accept", "application/xml"); 

     string content = "Here is my input string"; 
     StringContent sContent = new StringContent(content, Encoding.UTF8, "application/xml"); 

     HttpResponseMessage response = null; 
     string resultString = null; 

     client.PostAsync(new Uri(totalUrl), sContent).ContinueWith(responseMessage => 
      { 
       response = responseMessage.Result; 
      }).Wait(); 

     response.Content.ReadAsStringAsync().ContinueWith(stream => 
      { 
       resultString = stream.Result; 
      }).Wait();   
    } 

我是新來的MVC的Web API和使用的HttpClient - 任何幫助指引我在正確的方向將不勝感激。

回答

6

試試下面的代碼:

class Program { 

    static void Main(string[] args) { 

     HttpClient client = new HttpClient(); 
     var content = new StringContent("=Here is my input string"); 
     content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 
     client.PostAsync("http://localhost:2451/api/values", content) 
      .ContinueWith(task => { 

       var response = task.Result; 
       Console.WriteLine(response.Content.ReadAsStringAsync().Result); 
      }); 

     Console.ReadLine(); 
    } 
} 

看一看在「發送簡單的類型」這篇博客的部分:http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

+1

這是偉大的!我的原始代碼中的兩個缺失部分是等號(對於簡單類型)和ContentType。添加這兩個部分解決了問題。 – jtoth3

相關問題