Question

In my VS2013 Web Application I have many controllers like this:

[Route("Test/{param1}")]
public bool Test (Int32 Param1)
{   
  return true;  
}

I invoke the method from my client:

response = await client.GetAsync("TestCtrlClass/Test/1");

and all works nice.

Now, I need to pass an object to methods, so I put this:

[HttpPost]
[Route("Test2/{item}")]
public bool Test2([FromBody] ClassName item)
{
     return true;       
}

I invoke the method from my client:

HttpClient client = new HttpClient();
client.BaseAddress = ServerUri;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<ClassName>(Item, jsonFormatter);
response = await client.PostAsync("TestCtrlClass/Test2", content);

and i get 404 NOT FOUND.

this is my route configuration:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();

Why?

Thanks.

Was it helpful?

Solution

Note that you are sending a POST request with parameters in the body. That means that the URl you are posting to is TestCtrlClass/Test2, not TestCtrlClass/Test2/anything_here. So your attribute should be:

[HttpPost]
[Route("Test2")]
public bool Test2([FromBody] ClassName item)

Also I believe [FromBody] is not needed here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top