DEV Community

Chris Cooper
Chris Cooper

Posted on • Originally published at on

WebAPI Post with Body parameters

The other day I needed to create a POST API (WebApi) for a third part to consume and return data, simple! Well it was not as simple as I first thought, as they were not able to hit my API and was getting the "No HTTP resource was found that matches the request URI". This was down to the way I had created my API and the way they were sending the POST data.

Normally I create PPOST WebAPI with the parameters in the method and you send the parameters in the URL. (Get parameters) They were sending the parameters in the POST body not within the URL, so they were getting the error. So I needed to remove the parameters and get the parameters from the RequestContext.

HTTP POST method

This is the POST method with out any parameters and gets the request context out of the HTTP Post Request.

[HttpPost] public bool DeliveryReceipts() { var value = this.Request.GetRequestContext(); getPostContent(Request.Content); return true; }

Reading the context

Now that the context has been collected from the request. This method gets a string key\value for the parameters, sent in the request.

private async void getPostContent(HttpContent content) { DataClassesRequestParameterDataClass request = newDataClassesRequestParameterDataClass(); var contentString = await content.ReadAsStringAsync(); var contentElements = contentString.Split('&'); foreach(var element in contentElements) { var parameter = element.Split('='); if(parameter.Count()>0) { setDataClass(parameter[0], parameter[1], ref request); }//END if(parameter.Count()>0) }//END foreach(var element in contentElements) }

Collecting the value

This is a simple method that sets a veritable from the key found within the key\value string.

private void setDataClass(string parameter, string value, ref DataClassesRequestParameterDataClass request) { switch(parameter.ToLower().Trim()) { case "number": request.Number = value; break; case "userid": request.UserId = value; break; case "datetime": request.DateTime = value; break; case "status": request.Status= value; break; } }


I've never used this technique of making post methods, but in away this seems a bit more secure than setting the parameters in the method, just simple because no one will know which parameter are needed to work the method.

I'm sure this wont be the last time, I use the logic for a POST method.

Top comments (0)