KTOV
KTOV

Reputation: 704

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:

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

In my Startup.cs I have:

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(); picks up every controller in my api project. I remember in asp.net to add controllers you would have to call this line:

services.AddTransient<AccountController>();

You would have to namely add each controller, is there no way to do this in .NET Core 3?

Upvotes: 0

Views: 90

Answers (2)

Suresh Padala
Suresh Padala

Reputation: 26

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.

Upvotes: 0

Sh.Imran
Sh.Imran

Reputation: 1033

If you want that certain endpoints should not be hit, MVC provide provision to use attribute [NonAction]:

[NonAction]
public IActionResult Index()

The end points for which the attribute is used, would not be hit in the API call.

Upvotes: 3

Related Questions