1

我有一个看起来像这样的网络服务:

[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 或 fiddler 访问 Web 服务时,它会抛出 500,甚至无法访问我的方法。我添加了一堆日志记录并收到以下错误:

服务操作“PutSomeStuff”期望为输入参数“requestMessage”分配一个可分配给“String”类型的值,但接收到“HttpRequestMessage`1”类型的值。

更新:如果我将 TextToPut 变量设为自定义对象,它可以正常工作。如果它是像字符串这样的原始类型,它只会给我带来问题。

4

3 回答 3

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())));
于 2011-06-27T06:40:10.733 回答
0

它正在 uri 中寻找字符串theTextToPut

于 2011-06-24T01:27:22.363 回答
0

正如@axel22 所说,应用程序可能正在绑定theTextToPut到 URI。正如本文所述,简单类型默认绑定到 URI。

您可以使用FromBody 属性强制应用程序绑定theTextToPut到请求正文。

于 2016-04-05T09:30:33.120 回答