我最近问了一些关于创建 Web API 的最佳方法的问题,该 API 使用与我的主要 MVC 站点相同的 URL。我推断最好的方法是对我的 MVC 站点进行必要的更改以包含 Web API 和必要的路由。
我主要关注了How to add Web API to an existing ASP.NET MVC 4 Web Application project?但我遇到了问题。代码编译正常,它显然正在寻找路线,但我收到错误:
No HTTP resource was found that matches the request URI 'http://localhost:2242/api/value'. No type was found that matches the controller named 'value'.
我的 WebApiConfig:
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
我的 global.asax:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<ApplicationDbContext>(null);
}
}
我的 api Controller :
public class ValuesController1 : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
其他帖子证实这是一个正确且有效的设置...我创建了一个单独的 webapi 项目进行比较,这显然是正确的路由选择。最好将其构建到我的 MVC 网站中,有人有任何想法吗?本海报No type was found that matches controller有同样的问题,他找到的解决方案是将所有内容复制到一个新项目中....这真的不是我想做的事情/看看为什么我需要做。
请您参考如下方法:
我认为这是因为您的 Controller 名称:ValuesController1
Controller 必须以“Controller”为后缀,1 可能是导致问题的原因。
