0

Having previously worked in .NET Framework, I'm now getting started with .NET Core.

I am building an application that is both MVC and Web API, and some of my routing is not working.

Here is my controller code:

    [Route("api/[controller]")]
    [ApiController]
    public class ClientController : ControllerBase
    {
        private readonly ApplicationDbContext db;
        public ClientController(ApplicationDbContext context)
        {
            db = context;
        }

        [HttpGet]
        public ActionResult Get()
        {
            return Ok("get works");
        }

        [HttpGet]
        public ActionResult Test()
        {
            return Ok("test not working");
        }

        [HttpGet]
        [Route("api/client/input")]
        public ActionResult input(int id)
        {
            return Ok(string.Format("Your id: {0}", id));
        }
    }

And here is my startup.cs code:

    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.AddDbContext<ApplicationDbContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
  • https://localhost:5001/api/client works
  • https://localhost:5001/api/client/test 404 error
  • https://localhost:5001/api/client/2 404 error
  • https://localhost:5001/api/client?id=2 404 error

I have tried adding specific routes to my individual actions and that had no effect.

Thanks in advance.

1 Answer 1

1

You can not gain anything making route attribute like this for the controller

  [Route("api/[controller]")]
    [ApiController]
    public class ClientController : ControllerBase

You can remove any attribute routing from the controller with [ApiController] together or make it like this

   [Route("api/[controller]/[action]")]
    [ApiController]
    public class ClientController : ControllerBase

in this case you can use this variants

        [HttpGet]
        public ActionResult Get() //api/client/get
        //or
         [HttpGet("GetAll")]
        public ActionResult Get() //api/client/getall

        [HttpGet]
        public ActionResult Test() //api/client/test
        {
            return Ok("test not working");
        }

and fix input

        [HttpGet]
        [Route("~/api/client/input/{id}")] //api/client/input/4
        public ActionResult input(int id)

but it is the same

  [HttpGet]
  public ActionResult input(int id)
Sign up to request clarification or add additional context in comments.

4 Comments

If I remove the route on the controller it gives an error message: "Action 'ProductPOC.Controllers.API.ClientController.Get' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed." That suggests to me that I'd then have to add a route to every single endpoint within the controller which goes against trying to tie-in to some default routing.
@MarkSeymour You have to remove [ApiController] too as I asked you in the answer
@MarkSeymour Or better live apicontroller and add full routing [Route("api/[controller]/[action]")]
@MarkSeymour I am sorry, I didn' realize that you are using 3.1. Check my updated answer pls.

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.