要按名称将Web API路由到控制器的特定方法,可以使用ASP.NET Core中的特性路由。以下是一个示例解决方法:
首先,确保已添加Microsoft.AspNetCore.Mvc.Core NuGet包。
然后,创建一个控制器,并在控制器的方法上使用特性路由。例如:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet("method1")]
public IActionResult Method1()
{
return Ok("This is Method1");
}
[HttpGet("method2")]
public IActionResult Method2()
{
return Ok("This is Method2");
}
}
在上面的示例中,[HttpGet("method1")]
和[HttpGet("method2")]
特性分别将Method1
和Method2
方法路由到/api/MyController/method1
和/api/MyController/method2
。
最后,确保在Startup.cs文件中启用路由:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
通过以上步骤,您可以使用特性路由将Web API路由到控制器的特定方法。在浏览器中访问/api/MyController/method1
将调用Method1
方法,并返回"This is Method1"。类似地,访问/api/MyController/method2
将调用Method2
方法,并返回"This is Method2"。
上一篇:按名称将频道添加到类别中
下一篇:按名称将子项合并到未知父项