.net coreウェブアプリケーションで空のプロジェクトを作成すると下記の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 WebApplication1
{
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)
{
}
// 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.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
ConfigureServicesメソッド:
Configure メソッドの先に呼ばれアプリケーションで使用サービスをDI(依存性注入メカニズム)に追加する。
servieces(コンテナ)に独自のサービスを追加していく。
ConfigureServicesメソッドで良く使用されるもの:
//コントローラーを使用する
services.AddControllers();
//swaggerを使用する
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication2", Version = "v1" });
});
Configureメソッド:
HTTP リクエストにどのように応答するかを指定するために使用する。(HTTPリクエストパイプラインにモジュールを追加していく、そのモジュールをミドルウェアという)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
環境変数がDevelopment:(開発)だったらより詳細なエラーページを表示するメソッド
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
ルートurlにアクセスされたら”Hello World!”を返す
Configureメソッド で良く使用されるもの:
//swaggerの使用
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication2 v1"));
//ルーティング有効化
app.UseRouting();
//認証有効化
app.UseAuthorization();
//エントリーポイントにコントローラー使用
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});