2011-10-10 79 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); 

请,如果您有任何意见或知道什么在让我知道要去。