gpt4 book ai didi

c# - .NET Core 2.1 Web API 是否支持基于约定的路由?

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:22 24 4
gpt4 key购买 nike

我是 Web API 和 .net core 的新手,我有一个开发 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: Action 'myproject.Controllers.ValuesController.dummyaction (myproject)' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.

最佳答案

我是如何让它工作的

即使在使用 map route 之后,我仍然收到关于基于属性的路由的错误

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Values", action = "dummyaction" });
});

So in the error can you see this line "Action methods on controllers annotated with ApiControllerAttribute must be attribute routed."

现在在我的 Controller 中,我正在使用这个特定的注释/属性“[ApiController]”,通过删除它我能够执行基于约定的路由。

此外,我已将路线更新如下

app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller=Values}/{action=gogogo}/{id?}");
});

引用资料:

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.2#mixed-routing-attribute-routing-vs-conventional-routingsection(混合路由:属性路由 vs 常规路由)

asp.net core web api center routing

关于c# - .NET Core 2.1 Web API 是否支持基于约定的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57730797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com