Search code examples
.netasp.net-coreasp.net-mvc-routing

.NET Core and MVC project, api controller route not working


In a project (including MVC and Web API) created using VS 2017 when I've added a new controller the default route calls the Index() function to that new API controller but browsing to any other method fails.

API Code

namespace TestApi.Controllers
{
[Produces("application/json")]
[Route("api/TestAPI")]
public class TestAPIController : Controller
{
    public string Index()
    {
        //if (!_signInManager.IsSignedIn(User))
        //return RedirectToAction("Login", "Account");

        return "View()";
    }

    //[Route("GetTestData")]
    [HttpGet]
    private string GetTestData()
    {
        return "Data";
    }
}
}

And the code from Startup class is as follows:

 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.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        services.AddScoped<IUrlHelper>(factory =>
        {
            var actionContext = factory.GetService<IActionContextAccessor>()
                                       .ActionContext;
            return new UrlHelper(actionContext);
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });


    }
}

So browsing to "https://localhost:44314/api/TestAPI" works but when i try to browse to "https://localhost:44314/api/TestAPI/GetTestData" I get page not found error.

Thanks for help.


Solution

  • Could be that your GetTestData action method is private. Try making it public.