Get method not working in web api - c#

Hi I am developing one application in web api2 and angularjs. I have some routing problems in accessing urls from angularjs.
I am trying to access below url.
var url = '/api/projects/4/processes';
My controller code looks like below.
[RoutePrefix("api/processes")]
public class processesController : ApiController
{
[ActionName("projects/{projectsId}/processes")]
public HttpResponseMessage Get(int id)
{
return Request.CreateResponse(HttpStatusCode.OK, "");
}
}
I am getting 404 error. I am not able to hit the url.
This is my webapi.config file.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
//routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Any help would be appreciated.

First ensure that attribute routing is enabled before convention-based routes.
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
if the intended url is /api/projects/4/processes Then the given action needs to update its route template to match. The controller already has a route prefix but that can be overridden by prefixing the route template with the tilde ~
Use a tilde (~) on the method attribute to override the route prefix:
//GET /api/projects/4/processes
[HttpGet]
[Route("~/api/projects/{projectsId:int}/processes")]
public HttpResponseMessage Get(int projectsId) { ... }
Source: Attribute Routing in ASP.NET Web API 2

In your case, the URL should be,
http://yourUrl/api/processes?projectsId=yourValue
Also, change your ActionName to Route attribute,
[RoutePrefix("api/processes")]
public class ProcessesController : ApiController
{
[Route("projects/{projectsId}/processes"),HttpGet]
public HttpResponseMessage Get(int projectsId)
{
return Request.CreateResponse(HttpStatusCode.OK, "");
}
}
New URL - http://yourUrl/api/processes/projects/2/processes
More info on Attribute routing

Please make sure that attribute routing should be enabled before convention-based routes.
config.MapHttpAttributeRoutes();
then you can make routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Define Methods like :
//GET /api/projects/4/processes ([ActionName("projects/{projectsId}/processes")])
[RoutePrefix("api/processes")]
public class processesController : ApiController
{
[HttpGet]
[Route("~/api/projects/{projectId:int}/processes")]
public HttpResponseMessage Get(int projectId) { ... }
}

You have a route prefix, which means the url of action would be RoutePrefix + ActionRoute
i.e. HTTP GET api/processes/projects/{projectsId}/processes
Ref docs

Comment out the "[Authorize]" attribute on the ValuesController class was all I needed...
All credit to DotNetTutorials
From the article:
“api/{controller}/{id}”
At this point, if you use the following URI in the browser, you will get an error stating – Authorization has been denied for this request.
http://localhost:xxxxx/api/values
To get rid of this error, comment Authorize attribute on the ValuesController class. This is related to security which we will discuss in a later article.

Related

How do I not generate the default endpoints when using attribute routing?

I'm using attribute routing in a Web API controller (.NET Framework 4.5.2 - don't ask, I'm trying to get approval for time to move everything forward).
I have applied a [RoutePrefix] attribute to my ApiController.
I have two controller actions, both HttpGets. Each has a [Route] attribute applied.
I'm using Swagger to auto-generate docs. In the docs for this controller I see three endpoints listed - two for my controller actions, and another HttpGet with the bare controller route.
That is what I have is this:
[RoutePrefix("api/test/Tickets")]
public class TestTicketsController : ApiController
{
[HttpGet, Route("")]
public HttpResponseMessage GetTickets()
{
....
}
[HttpGet, Route("since")]
public HttpResponseMessage GetTicketsSince(string since)
{
....
}
}
And In the generated Swagger docs I see three endpoints:
GET api/test/Tickets
GET api/test/Tickets/since
GET api/TestTickets
This third endpoint, api/TestTickets, seems to be derived from the class name of the controller, ignored my routing attributes. And when I call it, I get an HTTP 200 with an empty body, despite not having defined an action for it.
Where is this coming from? And how can I stop it from being generated?
===
It was suggested that I remove the [HttpGet, Route("")] attribute. If I do, I get an error:
Multiple operations with path 'api/TestTickets' and method 'GET'.
It was also suggested that I include my WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new RedirectHandler((message => message.RequestUri.ToString()), "api/docs/index"));
var mediaType = new MediaTypeHeaderValue("application/json");
var formatter = new JsonMediaTypeFormatter();
formatter.SupportedMediaTypes.Clear();
formatter.SupportedMediaTypes.Add(mediaType);
config.Formatters.Clear();
config.Formatters.Add(formatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
If I comment-out the config.Routes.MapHttpRoute, the extra endpoint goes away.
Now it's just a matter of determining whether we have any controllers that expect this default endpoint to be there.
Thanks.
abdulg pointed out in a comment, rather than in an answer - default routes are configured in WebApiConfig.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Multiple actions were found that match the request But WebApiConfig is set

i'm using asp.net web api. And my problem is "Multiple actions were found that match the request" but i set route template already and in my controller i have 2 POST action
**WebApiConfig**
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
And this is my controller
1. [Route("{InsertRoadMap}")]
[HttpPost]
public mdRoadMapCallBack InsertRoadMap(mdEvent _mdEvent){
mdRoadMapCallBack _mdRoadMapCallBack = new mdRoadMapCallBack();
return _mdRoadMapCallBack;
}
2. [Route("{UpdateRoadMap}")]
[HttpPost]
public mdRoadMapCallBack UpdateRoadMap(mdEvent _mdEvent)
{
mdRoadMapCallBack _mdRoadMapCallBack = new mdRoadMapCallBack();
return _mdRoadMapCallBack;
}
What is wrong ? Please help. Thank you so much
The Route attribute doesn't seems to be implemented correctly.
Use it like this instead -
[Route("api/mycontroller/InsertRoadMap")]
[Route("api/mycontroller/UpdateRoadMap")]
Now you can browse like this - http://server/api/mycontroller/InsertRoadMap
You can also use RoutePrefix attribute at controller level so that you do not have to repeat api for every method.
[RoutePrefix("api")]
And then you can set routes like -
[Route("mycontroller/InsertRoadMap")]
[Route("mycontroller/UpdateRoadMap")]
See here and here some more information on attribute routing

WebAPI route to root URL

I have a WebAPI application that is used for some RESTful operations in the database. It works great, but I want to match a route with the root URL. For example, I want to go to the root of the site and see some useful information that are dynamically generated.
Currently, I have it setup so that it follows the standard convention of api/{controller}/{action}, but how can I show this information when navigated to the root instead of something like api/diagnostics/all?
Basically what I want is, when the user navigates to the root URL, I want to route that request to TestController.Index()
I have the following setup in the WebApiConfig.cs file:
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Index",
routeTemplate: "",
defaults: new { controller = "Test", action = "Index" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, controller = "Test" }
);
}
And this is what my TestController.cs looks like:
[RoutePrefix("api")]
public class TestController : ApiController
{
[Route("TestService"), HttpGet]
public string Index()
{
return "Service is running normally...";
}
}
You could also simply use ([Route("")]):
public class TestController : ApiController
{
[Route(""), HttpGet]
public string Index()
{
return "Service is running normally...";
}
}
You can add a route for the default URL in WebApiConfig.cs. Here's an example where the root URL is mapped to method HomeController.Index():
config.Routes.MapHttpRoute(
name: "Root",
routeTemplate: "", // indicates the root URL
defaults: new { controller = "Home", action = "Index" } // the controller action to handle this URL
);
Basically what I want is, when the user navigates to the root URL, I
want to route that request to TestController.Index()
In this case make sure that you have not decorated your TestController.Index action with this attribute:
[Route("TestService")]
So here's how your TestController might look like:
[RoutePrefix("api")]
public class TestController : ApiController
{
[HttpGet]
public string Index()
{
return "Service is running normally...";
}
}
And now simply navigate to / or /api.

Multiple actions were found that match the request when using actions in Route config

I'm currently building an API using Web API 2.2
I have the RESTful part of it working but now I need one non-RESTful controller:
public class PremisesController : ApiController
{
private PremiseService _service;
public PremisesController()
{
_service = new PremiseService();
}
[HttpGet]
public IHttpActionResult Premise(string id)
{
id = id.Replace(" ", String.Empty).ToUpper();
List<Premise> premises = _service.GetPremisesForPostcode(id);
return Ok(premises);
}
[HttpGet]
public IHttpActionResult Building(string id)
{
double premise = Convert.ToDouble(id);
Building building = _service.GetBuildingsForPremise(premise);
return Ok(building);
}
}
The routing config is as follows:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Im getting the error that it can't distinguish between the two methods when I initiate a GET action:
Multiple actions were found that match the request
So my question is Do I need to specify the Route attribute on top of each method and if yes, why? Doesn't the second route (ActionApi) deals with that situation?
EDIT:
I just tested you're code and it works the way it is... maybe just it is unclear.
/api/Premises/Premise/8 --> will take you to your first action
/api/Premises/Building/8 --> will take you to your second action
/api/Premises/8 --> will cause error because the routing will go to the first rule api/{controller}/{id} with a GET request, then he can't distinguish which of the actions you want because they both match the first route: (api/Premises/{id})
You could also use the RoutePrefix attribute on your controller.
[RoutePrefix("api/premises")]
public class PremisesController : ApiController
That combined with the route attribute would mean you shouldn't get multiple actions with the same route

Multiple actions were found that match the request in Web Api

I keep getting this error when I try to have 2 "Get" methods
Multiple actions were found that match the request: webapi
I been looking around at the other similar questions about this on stack but I don't get it.
I have 2 different names and using the "HttpGet" attribute
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[HttpGet]
public HttpResponseMessage FullDetails()
{
return null;
}
Your route map is probably something like this in WebApiConfig.cs:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Notice that the routeTemplate now includes an action. Lots more info here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Update:
Alright, now that I think I understand what you are after here is another take at this:
Perhaps you don't need the action url parameter and should describe the contents that you are after in another way. Since you are saying that the methods are returning data from the same entity then just let the parameters do the describing for you.
For example your two methods could be turned into:
public HttpResponseMessage Get()
{
return null;
}
public HttpResponseMessage Get(MyVm vm)
{
return null;
}
What kind of data are you passing in the MyVm object? If you are able to just pass variables through the URI, I would suggest going that route. Otherwise, you'll need to send the object in the body of the request and that isn't very HTTP of you when doing a GET (it works though, just use [FromBody] infront of MyVm).
Hopefully this illustrates that you can have multiple GET methods in a single controller without using the action name or even the [HttpGet] attribute.
Update as of Web API 2.
With this API config in your WebApiConfig.cs file:
public static void Register(HttpConfiguration config)
{
//// Web API routes
config.MapHttpAttributeRoutes(); //Don't miss this
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
You can route our controller like this:
[Route("api/ControllerName/Summary")]
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[Route("api/ControllerName/FullDetails")]
[HttpGet]
public HttpResponseMessage FullDetails()
{
return null;
}
Where ControllerName is the name of your controller (without "controller"). This will allow you to get each action with the route detailed above.
For further reading: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
In Web API (by default) methods are chosen based on a combination of HTTP method and route values.
MyVm looks like a complex object, read by formatter from the body so you have two identical methods in terms of route data (since neither of them has any parameters from the route) - which makes it impossible for the dispatcher (IHttpActionSelector) to match the appropriate one.
You need to differ them by either querystring or route parameter to resolve ambiguity.
After a lot of searching the web and trying to find the most suitable form for routing map
if have found the following
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id =RouteParameter.Optional }, new { id = #"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
These mapping applying to both action name mapping and basic http convention (GET,POST,PUT,DELETE)
This is the answer for everyone who knows everything is correct and has checked 50 times.....
Make sure you are not repeatedly looking at RouteConfig.cs.
The file you want to edit is named WebApiConfig.cs
Also, it should probably look exactly like this:
using System.Web.Http;
namespace My.Epic.Website
{
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 }
);
}
}
}
I could have saved myself about 3 hours.
It might be possible that your webmethods are being resolved to the same url. Have a look at the following link :-
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
So, you might need to add your methodname to your routing table.
Without using actions the options would be:
move one of the methods to a different controller, so that they don't clash.
use just one method that takes the param, and if it's null call the other method from your code.
This solution worked for me.
Please place Route2 first in WebApiConfig. Also Add HttpGet and HttpPost before each method and include controller name and method name in the url.
WebApiConfig =>
config.Routes.MapHttpRoute(
name: "MapByAction",
routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
Controller =>
public class ValuesController : ApiController
{
[HttpPost]
public string GetCustomer([FromBody] RequestModel req)
{
return "Customer";
}
[HttpPost]
public string GetCustomerList([FromBody] RequestModel req)
{
return "Customer List";
}
}
Url =>
http://localhost:7050/api/Values/GetCustomer
http://localhost:7050/api/Values/GetCustomerList
I found that that when I have two Get methods, one parameterless and one with a complex type as a parameter that I got the same error. I solved this by adding a dummy parameter of type int, named Id, as my first parameter, followed by my complex type parameter. I then added the complex type parameter to the route template. The following worked for me.
First get:
public IEnumerable<SearchItem> Get()
{
...
}
Second get:
public IEnumerable<SearchItem> Get(int id, [FromUri] List<string> layers)
{
...
}
WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{layers}",
defaults: new { id = RouteParameter.Optional, layers RouteParameter.Optional }
);
It is possible due to using MVC controller instead of Web API controller.
Check the namespace in Web API controller it should be as following
using System.Net;
using System.Net.Http;
using System.Web.Http;
If the namespace are as following then it is give above error in web api controller method calling
using System.Web;
using System.Web.Mvc;
Please check you have two methods which has the different name and same parameters.
If so please delete any of the method and try.
I've stumbled upon this problem while trying to augment my WebAPI controllers with extra actions.
Assume you would have
public IEnumerable<string> Get()
{
return this.Repository.GetAll();
}
[HttpGet]
public void ReSeed()
{
// Your custom action here
}
There are now two methods that satisfy the request for /api/controller which triggers the problem described by TS.
I didn't want to add "dummy" parameters to my additional actions so I looked into default actions and came up with:
[ActionName("builtin")]
public IEnumerable<string> Get()
{
return this.Repository.GetAll();
}
for the first method in combination with the "dual" route binding:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "builtin", id = RouteParameter.Optional },
constraints: new { id = #"\d+" });
config.Routes.MapHttpRoute(
name: "CustomActionApi",
routeTemplate: "api/{controller}/{action}");
Note that even though there is no "action" parameter in the first route template apparently you can still configure a default action allowing us to separate the routing of the "normal" WebAPI calls and the calls to the extra action.
In my Case Everything was right
1) Web Config was configured properly
2) Route prefix and Route attributes were proper
Still i was getting the error. In my Case "Route" attribute (by pressing F12) was point to System.Web.MVc but not System.Web.Http which caused the issue.
You can add [Route("api/[controller]/[action]")] to your controller class.
[Route("api/[controller]/[action]")]
[ApiController]
public class MySuperController : ControllerBase
{
...
}
I know it is an old question, but sometimes, when you use service resources like from AngularJS to connect to WebAPI, make sure you are using the correct route, other wise this error happens.
Make sure you do NOT decorate your Controller methods for the default GET|PUT|POST|DELETE actions with [HttpPost/Put/Get/Delete] attribute. I had added this attibute to my vanilla Post controller action and it caused a 404.
Hope this helps someone as it can be very frustrating and bring progress to a halt.
For example => TestController
[HttpGet]
public string TestMethod(int arg0)
{
return "";
}
[HttpGet]
public string TestMethod2(string arg0)
{
return "";
}
[HttpGet]
public string TestMethod3(int arg0,string arg1)
{
return "";
}
If you can only change WebApiConfig.cs file.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/",
defaults: null
);
Thats it :)
And Result :
Have you tried like:
[HttpGet("Summary")]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[HttpGet("FullDetails")]
public HttpResponseMessage FullDetails()
{
return null;
}

Categories