2011-10-10 98 views
1

我試圖在我的api中發佈一些使用WCF Web Api編程的信息。在客戶端中,我使用restsharp,這是restful服務的休息客戶端。但是,當我嘗試向請求中添加一些參數時,服務中的post方法從不會被調用,並且我的客戶端響應對象獲得500狀態(內部服務器錯誤),但是當我評論我所在的行時, m添加參數,請求到達服務中暴露的post方法。使用restsharp在WCF web api服務上發佈http

下面是來自客戶端的代碼:

[HttpPost] 
    public ActionResult Create(Game game) 
    { 
     if (ModelState.IsValid) 
     { 
      var request = new RestRequest(Method.POST); 
      var restClient = new RestClient(); 
      restClient.BaseUrl = "http://localhost:4778"; 
      request.Resource = "games"; 
      //request.AddParameter("Name", game.Name,ParameterType.GetOrPost); this is te line when commented  everything works fine 
      RestResponse<Game> g = restClient.Execute<Game>(request); 
      return RedirectToAction("Details", new {id=g.Data.Id }); 
     } 
     return View(game); 
    } 

下面是該服務的代碼:我需要這樣的服務的遊戲對象被填充到參數添加到我的要求

[WebInvoke(UriTemplate = "", Method = "POST")] 
    public HttpResponseMessage<Game> Post(Game game, HttpRequestMessage<Game> request) 
    { 
     if (null == game) 
     { 
      return new HttpResponseMessage<Game>(HttpStatusCode.BadRequest); 
     } 
     var db = new XBoxGames(); 
     game = db.Games.Add(game); 
     db.SaveChanges(); 

     HttpResponseMessage<Game> response = new HttpResponseMessage<Game>(game); 
     response.StatusCode = HttpStatusCode.Created; 

     var uriBuilder = new UriBuilder(request.RequestUri); 
     uriBuilder.Path = string.Format("games/{0}", game.Id); 
     response.Headers.Location = uriBuilder.Uri; 
     return response; 
    } 

,但我不知道如何做到這一點,如果服務每次嘗試添加參數時都會中斷。

我忘了提及客戶端和服務器都是.NET MVC 3應用程序。

任何幫助將不勝感激。提前致謝。

回答

1

我注意到你正在把Game作爲一個參數和HttpRequestMessage。你不需要這樣做。一旦你有請求(即你的請求參數),你可以在Content Property上調用ReadAs,你將得到Game實例。你傳球兩次的事實可能是造成這個問題的原因。你能否嘗試移除你的第二個遊戲參數,並使用響應中的那個參數? WCF Web API不支持表單url編碼。在預覽版5中,如果您使用MapServiceRoute擴展方法,它將自動連線。如果你不是,那麼創建一個WebApiConfiguration對象並將它傳遞給你的ServiceHostFactory/ServiceHost。

+0

問題解決了。非常感謝你! – Daniel

0

我不熟悉你打電話給的對象,但是是game.Name一個字符串?如果不是,這可能解釋爲什麼AddParameter失敗。

+0

是的,它是一個字符串。 – Daniel

1

那麼一遍又一遍地回答這個問題後,我終於找到了一個解決方案,但是,我無法解釋爲什麼會發生這種情況。

我替換addBody的addParameter方法,並且一切按預期工作,我可以在服務器上發佈信息。

問題似乎是,無論何時通過addParameter方法添加參數,此方法都會將參數附加爲application/x-www-form-urlencoded,顯然WCF web api不支持這種類型的數據,並且這就是爲什麼它向客戶端返回內部服務器錯誤。

相反,addBody方法使用服務器可以理解的text/xml。

同樣,我不知道這是不是真的發生了什麼,但似乎是這樣。

這是我的客戶端代碼現在的樣子:

[HttpPost]   
    public ActionResult Create(Game game) 
    { 
     if (ModelState.IsValid) 
     { 
      RestClient restClient = new RestClient("http://localhost:4778"); 
      RestRequest request = new RestRequest("games/daniel",Method.POST); 
      request.AddBody(game); 
      RestResponse response = restClient.Execute(request); 
      if (response.StatusCode != System.Net.HttpStatusCode.InternalServerError) 
      { 
       return RedirectToAction("Index"); 
      } 
     } 
     return View(game); 

請,如果您有任何意見或知道什麼在讓我知道要去。