Asp.net WebApi:找不到与名为'xxxx'的控制器匹配的类型

you*_*uen 7 c# asp.net asp.net-mvc asp.net-web-api

我有这个问题似乎很常见,但我读过的解决方案都没有在我的案例中起作用.我正在尝试在现有的MVC项目中添加ApiController.

当我尝试访问http:// localhost:51362/api/test上添加的控制器时,出现此错误:{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:51362/api/test'.","MessageDetail":"No type was found that matches the controller named 'test'."}

我的项目包含以下NuGet包:

  • Microsoft.AspNet.Mvc 5.2.3
  • Microsoft.AspNet.WebApi 5.2.3
  • Microsoft.AspNet.WebApi.Client 5.2.3
  • Microsoft.AspNet.WebApi.Core 5.2.3
  • Microsoft.AspNet.WebApi.WebHost 5.2.3

我的Global.asax.cs(摘录):

RouteTable.Routes.Clear();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteTable.Routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Run Code Online (Sandbox Code Playgroud)

我的WebApiConfig.cs:

using System.Web.Http;

namespace End.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的新控制器:

using System.Web.Http;

namespace End.Web.Controllers
{
    public class TestController : ApiController
    {
        public string Get()
        {
            return "ok";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也试过属性路由没有成功.我想做的事情似乎很简单.我错过了一些明显的东西吗

She*_*ror 6

我知道这是一个老问题,但由于它从未得到公认的答案,所以我会尝试一下。

我也有这个问题。对我来说,这解决了这个问题:

GlobalConfiguration.Configure(config =>
{
    config.Services.Replace(typeof(IHttpControllerTypeResolver), new DefaultHttpControllerTypeResolver());
    ...
});
Run Code Online (Sandbox Code Playgroud)

就我而言,WebHostHttpControllerTypeResolver使用的是而不是DefaultHttpControllerTypeResolverWebHostHttpControllerTypeResolver首先从缓存(文件)中读取控制器类型,如果该文件存在,则其内容被序列化并返回。如果文件不存在,则WebHostHttpControllerTypeResolver调用DefaultHttpControllerTypeResolver

我首先设置了 Web api,但没有任何 API 控制器,从而遇到了问题。这导致缓存的控制器类型列表为空,因此出现了问题。由于控制器类型缓存在文件中,因此即使您重新启动 Web API,其内容也不会被删除。

另一种解决方案可能是删除存储控制器类型缓存列表的文件。该文件被调用MS-ApiControllerTypeCache.xml并且应该位于文件夹中的某个位置C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root

WebHostHttpControllerTypeResolver.cs