尽管尝试了Stack Overflow中提供的不同解决方案,但我无法解决此问题。我试过了:
我的代码:
RouteConfig.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;
namespace Reviewed
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "GetReviewComments",
routeTemplate: "api/reviews/comments/{id}",
defaults: new { id = RouteParameter.Optional, controller = "Reviews", action = "Comments" }
);
routes.MapHttpRoute(
name: "GetByCategories",
routeTemplate: "api/reviews/categories/{category}",
defaults: new { category = RouteParameter.Optional, controller = "Reviews", action = "GetByCategory" }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
的Global.asax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Data.Entity;
using Reviewed.Models;
namespace Reviewed
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer(new ReviewedContextInitializer());
}
}
}
答案 0 :(得分:0)
我不明白WebApiConfig中的路由是什么。
没什么特别的,真的。
只有这个惯例才能将启动代码放在App_Start目录中的静态类方法中,并从Global.asax中调用它们。
这个约定在MVC 5 / WebAPI 2版本中略有改变,所以如果您使用过时的教程,或者在使用旧版本时使用较新版本,或者在项目中升级MVC版本,或添加WebAPI到现有的MVC项目可能最终会出现重复或错误的代码。如果您升级,请务必关注upgrade path。
鉴于您同时拥有WebApiConfig.Register(GlobalConfiguration.Configuration)
和RouteConfig.RegisterRoutes(RouteTable.Routes)
,您似乎已完成上述任务。
最后,这将导致此代码:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
要被调用两次,导致你看到的错误。