서버(Server)/Blazor
[Blazor] Blazor API 서버 Example
3DMP
2023. 4. 13. 11:00
ValuesController
using HelloEmpty.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace HelloEmpty.controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public List<HelloMessage> Get()
{
List<HelloMessage> message = new List<HelloMessage>();
message.Add(new HelloMessage() { Message = "Hello Web API 1!" });
message.Add(new HelloMessage() { Message = "Hello Web API 2!" });
message.Add(new HelloMessage() { Message = "Hello Web API 3!" });
return message;
}
}
}
get() 이 클라에서 서버로 api/Values 경로로 api 를 쏘면
서버에서 보낼 내용을 message 에 담아 브라우저에 보낸다
HelloMessage
namespace HelloEmpty.Models
{
public class HelloMessage
{
public string Message { get; set; }
}
}
실제 데이터는 Models 에 들어있게 된다
program 부분인데 이 부분은 디폴트이다
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HelloEmpty
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
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 HelloEmpty
{
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)
{
//mvc 를 사용하겠다는 것
//services.AddControllersWithViews();
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();
//endpoints.MapRazorPages();
//endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
/*
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
*/
});
}
}
}
DotNet Core 3.1 버전으로 하면 StartUp.cs 가 생성된다
실행결과
실제 데이터가 JSON 형태로 온것을 알 수 있다
반응형