Adding Web API Controller to an ASP.NET application

We just enabled and wired up the MVC service to our application. Now, let's add a Web API controller by following these steps:

  1. Right-click on the My Todo project, navigate to Add | New Folder, and name the folder Controllers:
Create a new folder for controllers under the My Todo project
  1. Now, right-click on the Controllers folder that we just created and go to Add | New Item:
Add the Web API controller to the Controllers folder
  1. Select Minimal Dependencies and click on Add if you get an Add MVC Dependencies popup:
Add minimal MVC dependencies

Visual Studio 2017 has added a ScaffoldingReadMe.txt readme file with the following instructions to enable scaffolding in our application; follow and update your project code accordingly.

ASP.NET MVC core dependencies have been added to the project. However, you may still need to make these changes to your project:

  1. Add Scaffolding CLI tool to the project:
    <ItemGroup>   
<DotNetCliToolReference
Include="Microsoft.VisualStudio.Web.CodeGeneration.
Tools" Version="1.0.0" />
</ItemGroup>
  1. These are the suggested changes to the Startup class:
    2.1 Add a constructor:   
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json",
optional: true,
reloadOnChange: true)
.AddJsonFile($"appsettings.
{env.EnvironmentName}.json", optional:
true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
2.2 Add MVC services:
public void ConfigureServices(IServiceCollection
services)
{
// Add framework services.
services.AddMvc();
}
2.3 Configure web app to use use Configuration and
use MVC routing:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory
loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection
("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "
{controller=Home}/{action=Index}
/{id?}");
});
}
  1. Again, right-click on the Controllers folder, go to Add | Controllers, select API Controller with read/write actions, and name it as TodosController:
Name the controller TodosController
If you get the error in the following screenshot, you need to add the given XML tag by editing your csproj file and then, add the controller again.

This is the error:

The following is the code for the XML tag:

<ItemGroup>   
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" />
</ItemGroup>

This will create the TodosController Web API controller with the following template code for us to modify according to our needs:

[Produces("application/json")]   
[Route("api/Todos")]
public class TodosController : Controller
{
// GET: api/Todos
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Todos/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
// POST: api/Todos
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT: api/Todos/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
  1. Press F5 to run the application and navigate to http://localhost:2524/api/todos from the browser.
You may have a different port in your system.

You will see the following output from TodosController as per the default code in the Get method. As you can see in the following screenshot, it just returned an array of string:

The output of the default Get action in TodoController
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.5.68