Today want to study the Web Api, write a test API, open the site after browsing, but the hint can not find the method, just beginning to think where the configuration is wrong, but found a half-day has not seen.
Because I was in an existing MVC site to do the demo, so plan to create a new MVC site, try again, the new site is normal, compared to the global file, found that Webapiconfig and routeconfig order is not the same.
If you put the new site Routeconfig also before the webapiconfig, the same hint that the method cannot be found. It seems that the two configurations are connected.
?
1 2 |
WebApiConfig.Register(GlobalConfiguration.Configuration); RouteConfig.RegisterRoutes(RouteTable.Routes); |
Look at the Globalconfiguration class and you'll see.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public static class GlobalConfiguration {
private static Lazy<HttpConfiguration> _configuration =
new Lazy<HttpConfiguration>(
delegate {
HttpConfiguration configuration =
new HttpConfiguration(
new HostedHttpRouteCollection(RouteTable.Routes));
configuration.Services.Replace(
typeof
(IAssembliesResolver),
new WebHostAssembliesResolver());
configuration.Services.Replace(
typeof
(IHttpControllerTypeResolver),
new WebHostHttpControllerTypeResolver());
configuration.Services.Replace(
typeof
(IHostBufferPolicySelector),
new WebHostBufferPolicySelector());
return configuration;
});
public static HttpConfiguration Configuration
{
get
{
return _configuration.Value;
}
}
//... }
|
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}"
);
routes.MapRoute(
name:
"Default"
,
url:
"t/{controller}/{action}/{id}"
,
defaults:
new { controller =
"Home"
, action =
"Index"
, id = UrlParameter.Optional }
);
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name:
"DefaultApi"
,
routeTemplate:
"api/{controller}/{id}"
,
defaults:
new { id = RouteParameter.Optional }
);
}
}
|
A similar route after merging:
1 routes. Maphttproute (2Name"Defaultapi",3Routetemplate:"Api/{controller}/{id}",4DefaultsNew{id =Routeparameter.optional}5 );6 routes. MapRoute (7Name"Default",8Url:"{Controller}/{action}/{id}",9DefaultsNew{controller ="Home", action ="Index", id =Urlparameter.optional}Ten);
If the order is reversed, Defaultapi's route will never match, and the route "{api}/{action}/{id}" of MVC is always looked for.