开发者

C# WCF Web API Problems Posting/Putting

I have a webservice that looks something like this:

[WebInvoke(UriTemplate = "/{userName}/?key={key}&machineName={machineName}", Method = "PUT")]
public HttpResponseMessage<SomeStuffPutResponse> PutSomeStuff(string userN开发者_运维百科ame, string key, string machineName, string theTextToPut)
{
     // do stuff
}

My global.asx looks like:

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

When I hit the webservice via C# HttpClient or fiddler it is throwing a 500 and not even getting to my method. I added a bunch of logging and am getting the following error:

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

UPDATE: If I make theTextToPut variable a custom object it works fine. It is just giving me issues if it is a primitive type like a string.


Solution 1.

You could change the theTextToPut-parameter to a HttpRequestMessage and then read the content of the message.

[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();
}

Solution 2.

If you really want to get the parameter as a string you could create a operation handler that handles all string parameters named "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();
        }
    }

Then you set up your service in Global.asax as follows:

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


It's looking for string theTextToPut in the uri.


As @axel22 says, probably the application is binding theTextToPut to the URI. As this article states, simple types are binded to the URI by default.

You could use FromBody attribute to force the application to bind theTextToPut to the request body.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜