0

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?

2
  • Is the issue that you can't hit your endpoint? - services.AddTransient<AccountController>(); is specifically DI and is not standard in .NET framework Commented Jul 18, 2020 at 18:50
  • @GlynnHurrell I can hit the endpoint, but removing app.UseEndpoints() won't allow me to hit the endpoints. I was thinking of a scenario where if I didn't want certain endpoints to be hit, how would I specify each controller to be used by the api? Commented Jul 18, 2020 at 19:03

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.