By testing and wasting obscene amount of time I have found out that ASP.NET MVC has a bug which prevents using the string "api" in request URL. I wan to access my method with URL like this
www.mysite.com/api/test
This is not an unexpected wish. In fact it an an obvious Url choice.
Is there a workaround to achieve this?
UPDATE
By request routing definition.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// this executes, checked it in debugger
routes.MapRoute(
name: "Test",
url: "api/test",
defaults: new { controller = "Api", action = "Test" }
);
}
ApiController
public class ApiController : Controller
{
public ActionResult Test()
{
return Content("TEST TEST TEST");
}
{
If you have the WebApi packages installed, you'll find a WebApiConfig.cs class in App_Start. Here's what it looks like:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
So, assuming you don't change the default code in Global.asax.cs, this route gets added to the routing table. Hence, why your /api/whatever route doesn't work.
If you're not using WebApi, I would suggest removing the packages. Otherwise, you can simply change the "root" part of the API route to something else:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
/* changed 'api' to 'restsvc' */
routeTemplate: "restsvc/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Related
I am trying to develop a webapi+angularjs+mvc project .here you can see my apicontroller
public class DefaultController : ApiController
{
testDBEntities a = new testDBEntities();
public IEnumerable<City> Get()
{
return a.Cities;
}
}
Here you can see the webapiconfig
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 }
);
}
}
But when i type this : localhost:5411/api/default
i got this 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: /api/default
Add the line
GlobalConfiguration.Configure(WebApiConfig.Register) in your Global.asax.cs file
And this will register the webapi routes
I have created a new controller called WebPortalController but when I call it or try to call it via the browser I couldnt access the below method just said resource is not found. Do I need to add a new routing to the RoutesConfig.cs code if so how.?
namespace WebApi.Controllers
{
public class WebPortalController : ApiController
{
// GET api/webportal
private WebPortEnterpriseManagementDa _da = new WebPortEnterpriseManagementDa();
public ManagedType Get(string name)
{
ManagedType items = _da.GetManagedType(name);
return items;
}
// POST api/webportal
public void Post([FromBody]string value)
{
}
// PUT api/webportal/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/webportal/5
public void Delete(int id)
{
}
}
}
Routes file
namespace WebApi
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
The route config you have shown is for MVC routes and is located in the App_Start/RouteConfig file. Check that you have a default API route set in your App_Start/WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Then you will need to change the parameter name in your Get method to match the routing parameter:
public ManagedType Get(string id)
{
ManagedType items = _da.GetManagedType(name);
return items;
}
This should allow you to call your Get method through a browser using:
localhost:55304/api/WebPortal/Test
In order to test out your Post/Put/Delete methods you will need to use Fiddler or a browser addin such as Postman
I have 2 controllers( and ApiController and a Controller). My ApiController calls a provider to get data from the database while my Controller returns a view. I have created separate route configs for them. However, it seems like it is having problems on identifying which route to use? I'm not really sure
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableSystemDiagnosticsTracing();
}
}
Global.asax.cs
public class WebApiApplication
{
protected void ApplicationStart()
{
WebApiAuthConfig.Register(GlobalConfiguration.Configuration);
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperConfig.RegisterMappings();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
The routes work fine when accessing within the project. However, when the HttpClient tries to contact the ApiController using the route stated above (Api/../..), it could not contact the controller. It seems like it's confused with the route.
Instead of setting up the standard web routing in the WebApi portion of the code, consider doing it the other way around, setting up WebApi routing in the standard web routing portion of the code. This works in a project I have access to:
public class MvcApplication : HttpApplication {
protected void Application_Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
...
}
}
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
}
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}
);
}
}
You might find it better to factor out your API into a separate project. You might then also need to factor out a common data access project that your Web and API projects both depend upon but the resulting rationalized structure will make it easier to resolve config issues of the sort you describe and build failures in one area e.g. API will not stop other projects building.
In WebApiConfig.cs, your routeTemplate should be api/{controller}/{action}/{id}
My VS project has the following folder and files:
~\Controllers
\AccountController.cs
\HomeController.cs
...
~\Data
\AccountController.cs
...
~\App_Start
\RouteConfig.cs
\WebApiConfig.cs
WebApiConfig.cs contains:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
~\Data\AcccountController.cs contains:
namespace myApp.Data
{
public class AccountController : ApiController
{
[HttpGet]
public string GetUser(int id)
{
//...
}
...
}
}
When I make a http call to /api/Account/GetUser, the call is routed to the GetUser method shown above. What in all of the above or any configuration file tells the server to take the action from this particular file? What if ~/Controllers/AccountController.cs also contain a method of the same name?
It is called convention over configuration.
I'm fighting issues with routing in an MVC 3 Web API. It seems like it should be pretty simple, but I'm not making any headway.
My error is:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'Boolean NewViolationsPublished(Int32)' in 'BPA.API.Controllers.CacheManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
My RegisterRoutes is such:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "NukeAllItemsFromCache",
routeTemplate: "api/CacheManagement/NukeAllItemsFromCache");
routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}"
);
routes.MapHttpRoute(
name: "ControllerAndActionAndId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "Get" },
constraints: new { id = #"^\d+$" } // Only integers
);
routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"^\d+$" } // Only integers
);
}
And my controller is (i took out the code for ease of reading):
public class CacheManagementController : ApiController
{
public CacheManagementController()
[HttpGet]
public bool NewViolationsPublished(int id)
[HttpGet]
public bool IsCached(CachedItemLabels label, int clientId)
[HttpGet]
public void RemoveItemFromCache(int clientId, CachedItemLabels cacheLabel, string test)
[HttpGet]
public string NukeAllItemsFromCache()
}
I get the error when I try to call:
http://localhost/api/CacheManagement/NukeAllItemsFromCache
TIA
Are you sure you're defining your routes in the right place? Web API routes should be configured using System.Web.Http.GlobalConfiguration.Configuration.Routes.MapHttpRoute (normally in a WebApiConfig.cs file in App_Start), as shown on http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api, which is different from the route configuration used by vanilla MVC.
I think you may just be hitting the default Web API route, which is api/{controller}/{id}, with ID optional. The action is determined by the HTTP verb, which in this case is GET, and all of your methods match that by virtue of the [HttpGet].
Edit: example
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalModifiers.ApplyGlobalConfiguration(this, true);
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "action-specific",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I beleave your problem is in this route:
routes.MapHttpRoute(
name: "ControllerAndActionAndId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "Get" },
constraints: new { id = #"^\d+$" } // Only integers
);
You specify id as an optional parameter and at the same time constrain it to actually be a non-nullable number. If /api/CacheManagement/NukeAllItemsFromCache is an exception, then add additional route for it, otherwise ease a constraint to something like #"^\d*$" if possible.
You are missing the default action for the route you configured:
routes.MapHttpRoute(
name: "NukeAllItemsFromCache",
routeTemplate: "api/CacheManagement/NukeAllItemsFromCache");
should be
routes.MapHttpRoute(
name: "NukeAllItemsFromCache",
routeTemplate: "api/CacheManagement/NukeAllItemsFromCache",
defaults: new { action = "NukeAllItemsFromCache" }
);
You tried to put parameter id as nullable like:
[HttpGet]
public bool NewViolationsPublished(int? id)
or
[HttpGet]
public bool NewViolationsPublished(Nullable<Int32> id)
Maybe this works...
Double check that your controller extends ApiController rather than Controller
public class CacheManagementController : ApiController
rather than
public class CacheManagementController : Controller