HI, I am trying to work with the Web API in C#, and when calling it using jquery I am getting the error "Multiple actions were found that match the request: in web API C#", so how to resolve this issue, here is my current code
public HttpResponseMessage Create(Student stu) { HttpResponseMessage result; try { //some code here } catch (Exception e) { result = Request.CreateResponse(HttpStatusCode.BadRequest, "Error"); } return result; } [System.Web.Http.HttpPost] public HttpResponseMessage Edit(Student stu) { HttpResponseMessage result; try { //Some code here result = Request.CreateResponse(HttpStatusCode.Created, blog); } catch (Exception e) { result = Request.CreateResponse(HttpStatusCode.BadRequest, "Error"); } return result; }
as you can there are two methods with same argument but different name and method type also, so what's the issue with the code, how to resolve this error?
If you haven't read CRUD with Web api article(error explained here), please check this article https://qawithexperts.com/article/asp.net/create-edit-delete-using-aspnet-web-api-jquery-datatable-ser/76
You may get an error "Multiple actions were found that match the request" if you have two methods of same types, as In Web API (by default) methods are chosen based on a combination of HTTP method and route values.
What you have shown is a route for MVC controllers. I hope you realize that Web API controllers are an entirely different thing. They have their own routes defined in the ~/App_Start/WebApiConfig.cs
Solution
Either change your RuoteConfig.cs to make this work
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
OR add Route
Attribute at the top of your method, something like this
[System.Web.Http.Route("api/ControllerApi/Edit")] // to avoid "Multiple actions were found that match the request Web API"
public HttpResponseMessage Edit(Student Stu)
{
//Code here
}
Above answer looks good, but there are few more points to consider, first check you are editing
WebApiConfig.cs
Use the below code
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
// api/Country/WithStates
config.Routes.MapHttpRoute(
name: "ControllerAndActionOnly",
routeTemplate: "api/{controller}/{action}",
defaults: new { },
constraints: new { action = @"^[a-zA-Z]+([\s][a-zA-Z]+)*$" });
config.Routes.MapHttpRoute(
name: "DefaultActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
OR
If you are using "Route" Attribute in ActionMethod, then be sure to check "Route
" attribute (by pressing F12) is pointed to
System.Web.Http
and not System.Web.MVC
, which can cause this issue.
Use attribute ActionName on top of method
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly