How can I MapHttpRoute POST perform a custom action using WebApi?

I am trying to understand the frenzy of web API routing.

When I try to publish the data as follows:

curl -v -d "test" http://localhost:8088/services/SendData 

I get 404 and the following error message:

 {"Message":"No HTTP resource was found that matches the request URI 'http://localhost:8088/services/SendData'.","MessageDetail":"No action was found on the controller 'Test' that matches the request."} 

Here is the code for my test server.

 public class TestController : ApiController { [HttpPost] public void SendData(string data) { Console.WriteLine(data); } } class Program { static void Main(string[] args) { var config = new HttpSelfHostConfiguration("http://localhost:8088"); config.Routes.MapHttpRoute( name: "API Default", routeTemplate:"services/SendData", defaults: new { controller = "Test", action = "SendData"}, constraints: null); using (var server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Press Enter to quit."); Console.ReadLine(); } } } 

More generally, why the ASP.NET team decided to make the MapHttpRoute method so confusing. Why are two anonymous objects required ... how should someone know what properties these objects really need?

MSDN does not give any help: http://msdn.microsoft.com/en-us/library/hh835483(v=vs.108).aspx

All the pain of a dynamically typed language without any benefit if you ask me ...

+4
source share
3 answers

Use this signature and it will work every time.

 public class TestController : ApiController { [HttpPost] [ActionName("SendData")] public HttpResponseMessage SendData(HttpRequestMessage request) { var data = request.Content.ReadAsStringAsync().Result; Console.WriteLine(data); } } 
+2
source

Agree with you, this is crazy, you need to specify that the data parameter should be associated with the POST payload, since the web API automatically assumes that it should be part of the query string (because it is a simple type):

 public void SendData([FromBody] string data) 

And to further aggravate the frenzy, you need to add the POST payload with = (yes, this is not a typo, this is an equal sign):

 curl -v -d "=test" http://localhost:8088/services/SendData 

You can learn more about insanity in this article .

Or stop the madness and try ServiceStack .

+8
source

Try the following change:

 public class TestController : ApiController { [HttpPost] [ActionName("SendData")] public void SendData(string data) { Console.WriteLine(data); } } 

The ActionName attribute may solve the problem. Otherwise, you can also use the Publish symbol.

 public void Post(string data) { Console.WriteLine(data); } 

And send the Http message directly to the "services" without SendData.

0
source

All Articles