我在Startup.cs中有以下代码:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "DefaultApi",
template: "api/{controller=Customers}/{id?}");
});
}
}
...并在project.json中声明了MVC依赖:
{
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3"
},
"frameworks": {
"aspnet50": { },
"aspnetcore50": { }
},
"bundleExclude": [
"node_modules",
"bower_components",
"**.kproj",
"**.user",
"**.vspscc"
],
"exclude": [
"wwwroot",
"node_modules",
"bower_components"
]
}
我有以下控制器:
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
namespace WebApplication1.Controllers
{
public class CustomersController : Controller
{
private List<Customer> _Customers = new List<Controllers.Customer>();
public CustomersController()
{
_Customers.Add(new Customer() { ID = 1, Name = "Fred" });
_Customers.Add(new Customer() { ID = 2, Name = "Bob" });
_Customers.Add(new Customer() { ID = 3, Name = "Tim" });
}
public List<Customer> Get()
{
return _Customers;
}
public Customer Get(int ID)
{
Customer Customer = _Customers.Find(c => c.ID == ID);
return Customer;
}
}
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}
}
...但是当我浏览/ api / customers或/ api / customers / 1时,我得到 404 Not Found
我遗失了什么?是否支持MVC6中的Web API路由表?
答案 0 :(得分:0)
如果您尝试将Asp.Net Web API移植到MVC 6,则需要Web API Compatibility Shim。默认的启动类代码解释了它
// Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
// You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
// services.AddWebApiConventions();
默认情况下,它已关闭。启用后,您可以将web api route配置为
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
// Uncomment the following line to add a route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
更多详情here
答案 1 :(得分:0)
我回答这个问题有点迟了,但你需要输入路由属性
[Route("api/[controller]")]
并从
中删除apitemplate: "api/{controller=Customers}/{id?}");