I have an example controller in my WebApi-project:
public class MilestonesController : ApiController
{
// GET api/milestones
public IEnumerable<string> Get()
{
return new string[] { "M#1", "M#2" };
}
// GET api/milestones/5
public string Get(int id)
{
return "M with {id}";
}
// POST api/milestones
public void Post([FromBody]string value)
{
}
// PUT api/milestones/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/milestones/5
public void Delete(int id)
{
}
}
If I try to navigate to it:
http://localhost:59493/api/milestones
I always get the error:
No HTTP resource was found that matches the request URI 'http://localhost:59493/api/milestones'.
No type was found that matches the controller named 'milestones'.
Thank you in advance!
Edit:
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: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Possible Solution:
I have deleted my project and I've created a new one (WebAPi project) and now it works. The WebApiConfig etc was the same, so I don't really know what was wrong with my first try
you're missing the 'api' section of the url from your route. Try something more like;
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Take a look at where you created that controller. Maybe it is not in the Controllers folder, different namespace or that controller class is nested into another class
Related
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.aspx
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Api Controller
[RoutePrefix("api/buyinsurance")]
public class buyinsuranceapi : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Calling API Url
Error image
I have added API controller in the existing MVC application that time I have faced an issue.
please if anyone has an idea give me suggestion
Based on documentaion
Attribute routing can be combined with convention-based routing. To
define convention-based routes, call the MapHttpRoute method.
I want every route to start with api. For example i want the route to be http://localhost:40000/api/client/{id}/batch/approve so here is my WebApiConfig class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Then in controller i have
public class BatchController : ApiController
{
private readonly MyService _service;
public BatchController(MyService service)
{
_service = service;
}
[HttpPost]
[Route("client/{id}/batch/approve")]
public async Task<IHttpActionResult> Approve(int id, RequestDTO request)
{
return Ok(await _service.Approve(clientID,request).ConfigureAwait(false));
}
When client invoke this route, it receives 404 Not Found response.
However if i prefix api in Route attribute like below then it worked
[Route("api/client/{id}/batch/approve")]
Why convention based routing not prefixing api to route, why i also need to explicitly add api prefix to Route attribute
You must set RoutePrefixAttribute for the controller:
[RoutePrefix("api")]
public class BatchController : ApiController
{
[HttpPost]
[Route("client/{id}/batch/approve")]
public async Task<IHttpActionResult> Approve(int id, RequestDTO request)
{
...
}
}
https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
I have this function:
protected void Application_Start()
{
Database.SetInitializer(new PersonDbInitializer());
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
The WebApiConfig is:
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}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
At some point in the code I want to loop through all register api routes.
Any idea how can i do it?
System.Web.Http.GlobalConfiguration is static and you can get all routes with
GlobalConfiguration.Configuration.Routes
foreach (System.Web.Http.Routing.IHttpRoute route in GlobalConfiguration.Configuration.Routes)
{
}
I have added a Api Controller in my asp.net mvc5 web project, along with other controllers...i am contstantly getting resource not found error. please point out mistakes i might be making...
following is my Register method for WebApi routes
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
here is the Global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//GlobalConfiguration.Configure(WebApiConfig.Register);
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
here is my Api controller class
public class SearchController : ApiController
{
public IEnumerable<string> GetSearch()
{
return new string[] { "value1", "value2" };
}
}
"http://sukhdev.com/api/search" is the url scheme i use to call web api, but it persistenly "The resource cannot be found."
Why did you commented //GlobalConfiguration.Configure(WebApiConfig.Register);
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I'm working on an ASP.NET MVC 3.0 application, using Ninject as my dependency injection framework.
So I've inherited my controller from NinjectHttpApplication like so:
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver(Kernel));
}
protected override Ninject.IKernel CreateKernel()
{
return new StandardKernel(new QueriesModule());
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
new string[] { typeof(HomeController).Namespace }
);
}
}
But whenever I run the application and try to browse to any of my controllers, I get the error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Home/Index
What's causing this and how do I fix it?
Turns out this was occurring because the NinjectHttpApplication class from which I'm inheriting is calling the OnApplicationStarted() method at startup. So the solution is to remove the Application_Start() method and move all that code into OnApplicationStarted().