Properties\launchSettings.json에서 launchUrl을 "swagger"에서 "api/todoitems"로 업데이트합니다.
"launchUrl": "api/todoitems",
// Properties/launchSettings.json
// http 8080 으로 변경
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:8080",
"sslPort": 0
}
},
"profiles": {
"WebApplication1": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/todoitems",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:8080",
"dotnetRunMessages": true
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/todoitems",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
namespace TodoApi.Models
{
public class TodoItem
{
public long Id { get; set; }
public string? Name { get; set; }
public bool IsComplete { get; set; }
}
}
NuGet 패키지 추가
TodoContext 데이터베이스 컨텍스트 추가
using Microsoft.EntityFrameworkCore;
using System.Diagnostics.CodeAnalysis;
namespace TodoApi.Models
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options)
: base(options)
{
}
public DbSet<TodoItem> TodoItems { get; set; } = null!;
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
//builder.Services.AddSwaggerGen(c =>
//{
// c.SwaggerDoc("v1", new() { Title = "TodoApi", Version = "v1" });
//});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseSwagger();
//app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TodoApi v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Controllers 폴더를 마우스 오른쪽 단추로 클릭합니다.
추가>스캐폴드 항목 새로 만들기를 선택합니다.
Entity Framework를 사용하며 동작이 포함된 API 컨트롤러를 선택하고 추가를 선택합니다.
Entity Framework를 사용하며 동작이 포함된 API 컨트롤러 추가 대화 상자에서:
모델 클래스에서 TodoItem(TodoApi.Models) 을 선택합니다.
데이터 컨텍스트 클래스에서 TodoContext(TodoApi.Models) 를 선택합니다.
추가를 선택합니다.
스캐폴딩 작업이 실패하는 경우 추가를 선택하여 스캐폴딩을 다시 시도합니다.
// nameof 연산자를 사용하도록 PostTodoItem의 return 문을 업데이트합니다.
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
{
_context.TodoItems.Add(todoItem);
await _context.SaveChangesAsync();
//return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
}
// http-repl을 사용하여 웹 API를 테스트합니다.
// 명령 프롬프트에서 다음 명령을 실행합니다.
dotnet tool install -g Microsoft.dotnet-httprepl
httprepl http://localhost:8080/api/todoitems
post -h Content-Type=application/json -c "{"name":"walk dog","isComplete":true}"