Gopi
Gopi

Reputation: 5877

Create a pure web API project from Empty project in ASP.Net Core

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.

Upvotes: 1

Views: 4470

Answers (2)

Ian1971
Ian1971

Reputation: 3696

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();
...

Upvotes: 1

Rena
Rena

Reputation: 36575

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

Upvotes: 2

Related Questions