I cannot for the life of me figure this out. I have a web api controller with Get and Post methods. The Get method works fine with and without parameters, but the post breaks when I try to add a String parameter to it. Below is my code.
Route:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = UrlParameter.Optional }
);
Controller:
public class AuditController : ApiController
{
public String Post(String test)
{
return "Success : " + test;
}
public String Get(String test)
{
return "Success : " + test;
}
}
Request:
var request = WebRequest.Create("http://localhost:42652/Audit");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("test=TEST");
}
WebResponse webResponse = request.GetResponse();
I've tried many variations on the request, I feel like there's something simple I'm missing. Thanks for your help.
Since you are expecting parameter test
to come from body of a request, you would need to decorate it with FromBody
attribute. Example: ([FromBody]String test)
. This is not true for other complex types, for example: Employee
class which is implicitly considered to be coming from Body.
Rearding GET request. It should be working only with test coming from query string /Audit?test=Mike
Following blog post has more details about parameter binding: http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
Also, I see that you are using WebRequest. Have you considered using HttpClient from System.Net.Http instead?
Change your AuditController
to include the FromBody
attribute :
public class AuditController : ApiController
{
public String Post([FromBody]String test)
{
return "Success : " + test;
}
public String Get(String test)
{
return "Success : " + test;
}
}
cf. http://msdn.microsoft.com/en-us/library/system.web.http.frombodyattribute(v=vs.108).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With