1

I would like to create a pure Web API project without any reference to MVC in ASP.Net Core. So I create a project by selecting the "Empty" template and added a ValuesController that inherits from ControllerBase but when I run the project and navigate to api/values, it only display the text Hello World! that is part of Startup.cs.

When I searched online, all the tutorials asks the user to select "API" project template that has references to the MVC things. So can someone help me to create ASP.Net Core Web API without any reference to MVC things. This will be used only to serve API requests and will not contain any views.

2

2 Answers 2

2

it only display the text Hello World! that is part of Startup.cs.

That is because the empty project generate the middleware by default,you could delete the middleware or set the app.UseMvc(); before the middleware:

1.Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    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.UseMvc();
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });         
}

2.ValuesController:

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    // GET: api/<controller>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

3.Result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You can also do it with ut app.UseMvc(); if you wanted to retain using endpoints

In ConfigureServices put

services.AddControllers();

In Configure Endpoints

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

Comments

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.