【发布时间】:2020-01-03 22:44:33
【问题描述】:
我是 Web API 和 .net 核心的新手,我的任务是开发 API。
所以我创建了一个默认的 Web API(框架:.NET Core 2.1)并尝试添加路由映射,但出现错误。
有人可以帮我安排路线。
注意:不能使用基于属性的路由,需要根据 MVC 中的约定处理路由
我的启动程序:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Values", action = "dummyaction" });
});
}
}
这是我得到的错误:
InvalidOperationException:操作“myproject.Controllers.ValuesController.dummyaction (myproject)”没有属性路由。使用 ApiControllerAttribute 注解的控制器上的操作方法必须是属性路由。
【问题讨论】:
-
为什么不能使用属性路由?无论如何,没有基于约定的路由,例如具有
Get、Post、Put、Delete等操作并让这些操作自动响应这些 HTTP 方法。 -
Chris Pratt 因此,如果我将所有操作方法替换为类似“dummyaction”的名称并在地图路线中,如果我将默认操作设置为“dummyaction”,我将能够执行基于约定的路由
-
我不确定你在说什么。
标签: c# .net asp.net-core asp.net-web-api asp.net-web-api-routing