Konrad Viltersten Konrad Viltersten - 1 year ago 126
C# Question

Troubleshooting a ridiculously simple WebApi in VS Code on NET.Core

I have a working webpage (front-end strictly) and I was curious of I could add a WebApi without leaving VS Code. So I created a directory called webapi in the root of my project and added a file demo.cs containing the following.

using Microsoft.AspNetCore.Mvc;
namespace WebApi
public class Demo : Controller
[HttpGet] public string Ping() { return "yo!"; }

After some googlearching for references, I made sure that my project.json contains the following.

"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.AspNetCore.Mvc.Core": "1.0.1",

I also edited the configuration methods like this.

public void ConfigureServices(IServiceCollection services)

public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)

if (env.IsDevelopment())


Now, as I execute the project with dotnet run, I get no errors, the page functions but I can't seem to access the text I meant to expose. The extra problem's that I'm not sure if I've got the WebApi running but using the wrong URL (I went localhost:port with /api/donkey) or if it's not running at all.

How can I verify that it's up? What would be the address? Is there something else I'm missing in the setup?

The guides tell partially different things, which I guess depends on the rapid evolution of NET.Core. Not sure how to proceed.

Answer Source

Using documentation from

Routing to Controller Actions

To make attribute routing less repetitive, route attributes on the controller are combined with route attributes on the individual actions. Any route templates defined on the controller are prepended to route templates on the actions. Placing a route attribute on the controller makes all actions in the controller use attribute routing.

using Microsoft.AspNetCore.Mvc;
namespace WebApi {    
    public class Demo : Controller {    
        [HttpGet] // Matches 'GET /api/Demo'
        public string Ping() { 
            return "yo!"; 

the start up should have this in the configure services

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
    // Add framework services.
    //...other code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download