2013-04-21 702 views
3

我使用的Web API selef主持人:的StatusCode:404,ReasonPhrase: '未找到',版本:1.1,

public class TestController : ApiController 
{ 
    [HttpPost] 
    public void Testp([FromBody]string title) 
    { 
     Console.WriteLine("Post"); 
    } 
} 

這是簡單的控制器 ,這是我的客戶:

client.BaseAddress = new Uri("http://localhost:1010"); 
     const string englishTitle = "TesteDelete"; 
     var post = client.PostAsync("Test/Testp", new 
     { 
        title = englishTitle 
       }, new JsonMediaTypeFormatter()); 
       var result = post.Result; 
       if (result.IsSuccessStatusCode) 
       { 

       } 
       else 
       { 
        string content = result.Content.ReadAsStringAsync().Result; 

       } 

爲什麼我的結果是:

{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Date: Sun, 21 Apr 2013 12:00:03 GMT 
    Server: Microsoft-HTTPAPI/2.0 
    Content-Length: 165 
    Content-Type: application/json; charset=utf-8 
}} 

我thnik我ModelBinder的有一些錯誤

+0

我注意到你沒有用「/」結束你的基礎uri, – eaglei22 2017-05-25 22:46:52

回答

4

我想象你正在使用Visual Studio Web服務器進行調試(按時鐘)。此端口可以隨時更改,所以我猜它不再是「1010」作爲您的網址定義:

"http://localhost:1010"

也許你應該look here自動獲取當前的URL。

1
  1. 如果您使用的是默認的路由,它是基於REST(通過HTTP動詞,而不是RPC,通過方法名稱),所以你不應該張貼到http://localhost:1010/Test/Testphttp://localhost:1010/Test

  2. 你的行動簽名採用一個字符串,但是您正在發佈一個匿名對象。 您的文章應該是這樣的(請注意,我們只發送字符串):

    var post = client.PostAsync("Test", englishTitle, new JsonMediaTypeFormatter());

1

我想通了,我的問題是,如果我沒有結束基準URI以「/」並試圖預先掛起它client.PostAsync(..它是行不通但是,如果我追加到基本URI會像現在這樣,

using (HttpClient client = new HttpClient(handler) { BaseAddress = new Uri("https://test.test.com/somepath/") }) 
var response = client.PostAsync("Broadcast/Order", content).Result; 

工作,同時:

using (HttpClient client = new HttpClient(handler) { BaseAddress = new Uri("https://test.test.com/somepath") }) 
var response = client.PostAsync("/Broadcast/Order", content).Result; 

不。不知道爲什麼,但很高興我認爲它非常快!