简体   繁体   中英

Web API POST - 404 Not Found

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM