I have created a ASP.NET MVC5 web application and then added HelpPages and Web Api components. The MVC web app and HelpPages worked fine, but I couldn't reach to the API Controller via http://localhost:port/api/Samples/GetAll
. What can be wrong and how can I troubleshoot this?
WebApiConfig.cs
namespace MySolution.ApiV1
{
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
}
}
API Controller
namespace MySolution.ApiV1.Controllers.Api
{
[System.Web.Http.RoutePrefix("api/Samples")]
public class SamplesController : System.Web.Http.ApiController
{
[System.Web.Http.HttpGet]
[System.Web.Http.Route("GetAll")]
public System.Web.Http.IHttpActionResult Get()
{
return Ok("Hello Web API!");
}
}
}
Global.ascx.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
答案 0 :(得分:0)
I found the problem. The web api route must be called before the mvc route. I don't know why it makes a differences, but after I swap the orders, it worked.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register); // call first
RouteConfig.RegisterRoutes(RouteTable.Routes); // call second
BundleConfig.RegisterBundles(BundleTable.Bundles);
}