Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF REST Service: How to make query parameters required and return HTTP 400 on wrong values?

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.

like image 237
AndiDog Avatar asked Dec 06 '25 12:12

AndiDog


1 Answers

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.

like image 73
Rajesh Avatar answered Dec 09 '25 02:12

Rajesh