'ASP.NET Core dual routes for web and api

This is for an ASP.NET Core application. A json Web API needs to be added alongside a normal website.

So in program.cs, a second route was added:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(name: "default",
    pattern{controller=Home}/{action=Index}/{id?}");

//2nd route for web api
app.MapControllerRoute(name: "api", 
    pattern: "{controller=WebApi}/{Action}/{country?}/{id?}");

app.MapRazorPages();
app.Run();

The Web API WebApicontroller was written, and the class starts as below - noting the [ brackets ] syntax.

using System.Web.Http;
using Microsoft.AspNetCore.Http;
 
namespace myprogram.Controllers
{
    // [System.Web.Http.Route("[controller]/[action]/{id}")]  
    [Microsoft.AspNetCore.Components.Route("[controller]/[action]/{id}")]
    public class WebApiController : ApiController
    {
        // http://localhost:53912/webapi/Test
        [System.Web.Http.HttpGet]
        [System.Web.Http.ActionName("Test")]
        public string Test()
        return "Tested"; 
    }
}

Opening a page alike http://localhost:53912/webapi/test doesn't work.
What am I missing? I must be overlooking something here.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source