2011-06-24 57 views
1

我有一個Web服務,看起來是這樣的:C#WCF的Web API的問題發佈/把

[WebInvoke(UriTemplate = "/{userName}/?key={key}&machineName={machineName}", Method = "PUT")] 
public HttpResponseMessage<SomeStuffPutResponse> PutSomeStuff(string userName, string key, string machineName, string theTextToPut) 
{ 
    // do stuff 
} 

我global.asx樣子:

RouteTable.Routes.MapServiceRoute<SomeStuffService>("1.0/SomeStuff", new HttpHostConfiguration()); 

當我打通過C#HttpClient的web服務或提琴手投擲500,甚至沒有得到我的方法。我加了一堆的日誌記錄和正在以下錯誤:

The service operation 'PutSomeStuff' expected a value assignable to type 'String' for input parameter 'requestMessage' but received a value of type 'HttpRequestMessage`1'.

UPDATE:如果我讓theTextToPut變量的自定義對象,它工作正常。它只是給我的問題,如果它是一個像字符串的原始類型。

回答

0

它正在尋找字符串theTextToPut在uri。

+1

如何指定我希望該字符串位於請求正文中而不是URI。 –

2

解決方法1.

您可以在theTextToPut參數更改爲HttpRequestMessage,然後閱讀消息的內容。

[WebInvoke(UriTemplate = "/{userName}/?key={key}&machineName={machineName}", Method = "PUT")] 
public HttpResponseMessage<SomeStuffPutResponse> PutSomeStuff(string userName, string key, string machineName, HttpRequestMessage request) 
{ 
    string theTextToPut = request.Content.ReadAsString(); 
} 

解決方案2.

如果你真的想要得到的參數,你可以創建一個處理一個名爲「theTextToPut」所有的字符串參數的操作處理的字符串。

public class TextToPutOperationHandler : HttpOperationHandler<HttpRequestMessage, string> 
    { 
     public TextToPutOperationHandler() 
      : this("theTextToPut") 
     { } 

     private TextToPutOperationHandler(string outputParameterName) 
      : base(outputParameterName) 
     { } 

     public override string OnHandle(HttpRequestMessage input) 
     { 
      return input.Content.ReadAsString(); 
     } 
    } 

然後你在Global.asax中設置您的服務如下:

RouteTable.Routes.MapServiceRoute<SomeStuffService>("1.0/SomeStuff", 
       new HttpHostConfiguration().AddRequestHandlers(x => x.Add(new TextToPutOperationHandler()))); 
0

正如@ axel22說,可能是應用程序綁定theTextToPut到URI。由於this article states,簡單類型默認綁定到URI。

您可以使用FromBody attribute強制應用程序將theTextToPut綁定到請求正文。