3

1. Required parameter

In the following example URI definition

[WebGet(UriTemplate = "GetData?value={value}")]
[OperationContract]
string GetData(int value);
{
    return string.Format("You entered: {0}, value);
}

the "value" parameter is optional by default, and if I don't pass it (call to http://baseAddress/GetData), the variable is filled with zero.

Is there any easy way to make this parameter required, maybe an attribute? The only way I found is to manually check WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["value"] != null.

2. HTTP 400 on wrong format

Another thing I hate is that HTTP 500 is returned for /GetData?value=emptyOrAnythingThatIsNotAnInteger. Can I return HTTP 400 instead? Of course without changing the type to string and checking everything manually.

AndiDog
  • 68,631
  • 21
  • 159
  • 205

2 Answers2

1

you can use a string rather than an int and then perform your own validation and type coercion (the string will be null if not passed). Then you can return a 400 if the parameters are incorrect

Richard Blewett
  • 6,089
  • 1
  • 18
  • 23
  • Not really what I want, because in a usual WCF scenario, you would reuse the contract interface for the client, too. The string type essentially breaks type correctness here and introduces necessary manual checks. A bit too much stress for a simple parameter. – AndiDog Jan 24 '12 at 13:51
  • But this is input validation on a string value (the uri is a string) and therefore you have to be able to cater for the format of that data being incorrect. Also I'd personally not use the WebChannelFactory mechanism for client invocation but rather look at embracing HTTP with something like the HttpClient class from the new Web API. – Richard Blewett Jan 24 '12 at 14:24
1

The reason for a 500 error when you pass something other than integer is that WCF tries to parse the value passed into an integer and at this stage your request is already received and has been started for processing by the service.

You get a 400 error only when the message is on the channel and WCF doesn't understand the message format of the incoming message and that it needs to convert as specified by the service.

In order to inspect your value and return a 400 error try to use "MessageInspectors" where you have methods like "AfterReceiveRequest" by IDispatcherMessageInspector. Some info on Message inspectors can be found here.

Rajesh
  • 7,766
  • 5
  • 22
  • 35
  • Very complicated with WCF :( I ended up using ServiceStack instead of WCF because it allows more customization (request filters, attributes etc.) – AndiDog Jan 30 '12 at 10:15