简体   繁体   English

ASP.NET 核心3 API 路由

[英]ASP.NET Core 3 API routing

So I've created an API project using .NET Core 3 and inside the project I've created a Controller like so:因此,我使用 .NET Core 3 创建了一个 API 项目,并在项目内部创建了一个 Controller,如下所示:

[Route("api/account")]
[ApiController]
public class AccountController : ControllerBase
{
   public IActionResult Hello()
   {
      return Ok("Hello");
   }
}

In my Startup.cs I have:在我的Startup.cs中,我有:

public class Startup
{
   public IConfiguration Configuration { get; }

   public Startup(IConfiguration configuration)
   {
      Configuration = configuration;
   }

   public void ConfigureServices(IServiceCollection services)
   {
      services.AddControllers();
   }

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   {
      app.UseRouting();
      app.UseEndpoints(endpoints =>
      {
         endpoints.MapControllers();
      });
    }
}

From what I understand, the line services.AddControllers();据我了解,行services.AddControllers(); picks up every controller in my api project.在我的 api 项目中拾取每个 controller。 I remember in asp.net to add controllers you would have to call this line:我记得在 asp.net 要添加控制器,您必须调用此行:

services.AddTransient<AccountController>();

You would have to namely add each controller, is there no way to do this in .NET Core 3?您将不得不添加每个 controller,在 .NET Core 3 中没有办法做到这一点吗?

If you want that certain endpoints should not be hit, MVC provide provision to use attribute [NonAction] :如果您希望不命中某些端点,MVC 提供使用属性[NonAction]的规定:

[NonAction]
public IActionResult Index()

The end points for which the attribute is used, would not be hit in the API call.使用该属性的端点不会在 API 调用中命中。

If you don't want to expose an action method(end point) to client, you can make the method as "private" or as Imran suggested, you can decorate the method with "[NonAction]" attribute.如果您不想向客户端公开操作方法(端点),您可以将该方法设为“私有”或按照 Imran 的建议,您可以使用“[NonAction]”属性装饰该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM