-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartup.cs
197 lines (166 loc) · 6.7 KB
/
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*
* USESWAGGER makro pitää määritellä seuraavissa tiedostoissa:
* Startup.cs, PictureServerController.cs.
*/
//Käytä swaggeria
//#define USESWAGGER
//Käytä itse koodaamaasi frontendiä
#undef USESWAGGER
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using Microsoft.AspNetCore.Diagnostics;
using Picture_Catalog;
using Microsoft.OpenApi.Models;
using System.Linq;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using System;
using System.Text;
using static Picture_Catalog.Controllers.PictureServerController;
using System.Text.Json;
namespace Picture_Catalog
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#if USESWAGGER
services.AddMvc();
#endif
#if !USESWAGGER
services.AddControllersWithViews();
#endif
#if USESWAGGER
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "PictureCatalog API",
Description = "Example of ASP.NET Core Web API"
});
// c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
});
#endif
//Tämä lisää MySQL tietokantakontekstin.
services.AddDbContextPool<PictureDatabase>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
/*
//Tämä lisää MySQL tietokantakontekstin
services.AddDbContextPool<PictureDatabase>(options => options.UseMySql(
Configuration.GetConnectionString("DefaultConnection")
));
*/
//Raakadatan kuljettamiseen POST-komennon bodyssa tarvitaan oma inputformatteri.
services.AddMvc(
o =>
{
o.InputFormatters.Add(new RawRequestBodyFormatter());
}
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
#if USESWAGGER
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "PictureCatalog Test API v1");
// c.SwaggerEndpoint("./v1/swagger.json", "PictureCatalog Test API v1");
c.RoutePrefix = string.Empty;
});
#endif
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage(); //Default exception handler.
Exceptions(app, env);
}
else
{
//app.UseExceptionHandler("/Error"); //Default exception handler.
Exceptions(app, env);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
/// <summary>
/// Tämä funktio käsittelee serverin virhetilanteet ja lähettää niistä informaation
/// frontendiin. Jos serveriä ajetaan development-tilassa, frontendiin lähetetään
/// yksityiskohtaisempaa tietoa virheestä.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
private void Exceptions(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
IExceptionHandlerFeature except = context.Features.Get<IExceptionHandlerFeature>();
if (except != null)
{
// Viestiteksti sisältää sekä virhekoodin että virhekuvauksen.
string[] text = except.Error.Message.Split("@", 2, StringSplitOptions.None);
int code = 500;
if (!int.TryParse(text[0], out code)) code = 500;
context.Response.ContentType = "application/problem+json";
context.Response.StatusCode = code;
// Tämä viesti lähetetään sekä deployment että development tilassa.
Error error = new Error()
{
mCode = code,
mMessage = text[1],
mDetails = null
};
// Jos kyseessä on development-tila, viestiin lisätään lisätietoa,
// mikäli InnerException ei ole null.
if (env.IsDevelopment() && except.Error.InnerException != null)
{
error.mDetails = except.Error.InnerException.Message;
}
// Serialisoidaan responseen body.
var stream = context.Response.Body;
await JsonSerializer.SerializeAsync(stream, error);
}
});
});
}
}
}