Pages
- M
- Model
- defines Data
- C
- Controller
- defines Action
- No View!
- This is for data commnication
- It doen’t need UI
Code
- Controllers\ValueController.cs
using HelloEmptyWebAPI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HelloEmptyWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public List<HelloMessage> Get()
{
List<HelloMessage> messages = new List<HelloMessage>();
messages.Add(new HelloMessage() { Message = "Hello Web API 1!" });
messages.Add(new HelloMessage() { Message = "Hello Web API 2!" });
messages.Add(new HelloMessage() { Message = "Hello Web API 3!" });
return messages;
}
}
}
- Models\HelloMessage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HelloEmptyWebAPI.Models
{
public class HelloMessage
{
public string Message { get; set; }
}
}
- Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HelloEmptyRazor
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
}
}
}
}
Route
- [Route(string)]
- define how to match urls
- In Web API, it match urls with controllers’ name
[Route("api/[controller]")]
API Controller
- ApiController Attribute
- The [ApiController] attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:
Attribute routing requirement
Automatic HTTP 400 responses
Binding source parameter inference
Multipart/form-data request inference
Problem details for error status codes
- The [ApiController] attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:
[ApiController]
Startup.cs
- AddControllers
- Adds services for controllers to the specified IServiceCollection.
- MapControllers
- Adds endpoints for controller actions to the IEndpointRouteBuilder without specifying any routes.
- Rounting is in Controller
services.AddControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Result
