1
votes

Can not route directly to an api endpoint.

My api controller "TestController" should be found at localhost:5511/api/Test/getCollection?testCode=A but it wont route and retuns a 404.

I've a .net core 3.0 RazorPages app but need to include a few api endpoints. I don't think my endpoint is getting routed. In Startup.cs Configure method I have this:

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();               
});

Here is my route attribute on controller:

[Route("api/[controller]/[action]")]

GetCollection Action:

[HttpGet]
public IActionResult GetCollection(string testCode)
{

    List<string> retval = ...get a string list

    return Ok(retval);
}

[Edit]
------- ok a simpler example, wont route to api ---------
Razor pages .net core 3.0 app, add a new folder /api with a controller

Get a 404 when going to
https://localhost:44340/api/lookup/getsomething

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            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("/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.MapRazorPages();
            });
        }

api controller

namespace aspnetcore1.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class LookupController : ControllerBase
    {

        [HttpGet]
        [Route("GetSomething")]
        public IActionResult GetSomething()
        {
            return Ok("this is a test");
        }
    }
}
1

1 Answers

1
votes

Your route attribute on the controller should be:

[Route("api/Test")]

And the route attribute on the method should be:

[HttpGet]
[Route("GetCollection")]
public IActionResult GetCollection(string testCode)
{

    List<string> retval = ...get a string list

    return Ok(retval);
}

Edit

It looks like this is missing in the Configure(IApplicationBuilder app, IWebHostEnvironment env) method:

app.UseMvc();