-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStartup.cs
186 lines (155 loc) · 6.48 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
namespace TheWorld
{
using Models;
using Services;
using Newtonsoft.Json.Serialization;
using AutoMapper;
using ViewModels;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.Cookies;
public class Startup
{
private IHostingEnvironment _env;
private IConfigurationRoot _config;
public Startup(IHostingEnvironment env)
{
_env = env;
var builder = new ConfigurationBuilder()
.SetBasePath(_env.ContentRootPath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
_config = builder.Build();
}
/// <summary>
// 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 http://go.microsoft.com/fwlink/?LinkID=398940
/// </summary>
/// <param name="services"><see cref="IServiceCollection"/> </param>
public void ConfigureServices(IServiceCollection services)
{
// This method is the dependency injection layer.
services.AddSingleton(_config);
//_env.IsEnviornment("WhateverServer")
if (_env.IsDevelopment())
{
// We only want the IMailService to be available in the scope of the controller.
// AddSingleton and AddTransient as other options.
services.AddScoped<IMailService, DebugMailService>();
}
else
{
//TODO: Implement a real mail service.
}
services.AddDbContext<WorldContext>();
// This is Scoped because the initialization could be costly.
// We could also add a mock repository here for testing.
services.AddScoped<IWorldRepository, WorldRepository>();
// Transient since it is stateless.
services.AddTransient<GeoCoordsService>();
// Transient because this data gets created everytime we need it.
services.AddTransient<WorldContextSeedData>();
services.AddIdentity<WorldUser, IdentityRole>(config =>
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 8;
config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = async ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 401;
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
await Task.Yield();
}
};
})
.AddEntityFrameworkStores<WorldContext>();
services.AddLogging();
// Dependency injection and thus we need to add MVC.
services.AddMvc(config =>
{
// Machine this is hosted on should have ASPNETCORE_ENVIRONMENT=Production once released.
if (_env.IsProduction())
{
config.Filters.Add(new RequireHttpsAttribute());
}
})
.AddJsonOptions(config =>
{
config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// This is where the middle-ware is applied. Order matters.
/// </summary>
/// <param name="app"><see cref="IApplicationBuilder"/> </param>
/// <param name="env"><see cref="IHostingEnvironment"/></param>
/// <param name="loggerFactory"><see cref="ILoggerFactory"/></param>
/// <param name="seeder"><see cref="WorldContextSeedData"/></param>
/// <param name="logFactory"><see cref="ILoggerFactory"/></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, WorldContextSeedData seeder, ILoggerFactory logFactory)
{
loggerFactory.AddConsole();
// Middle-ware
//app.UseDefaultFiles(); // Should be first when using just static files.
// For debugging:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
logFactory.AddDebug(LogLevel.Information);
}
else
{
logFactory.AddDebug(LogLevel.Error);
}
Mapper.Initialize(config =>
{
// We create a map from TripViewModels to Trip and Trip to TripViewModels with ReverseMap call.
// Will also create mappings for collections of these types.
config.CreateMap<TripViewModels, Trip>().ReverseMap();
config.CreateMap<StopViewModel, Stop>().ReverseMap();
});
app.UseStaticFiles();
// Turn on use of ASP.NET Identity
app.UseIdentity();
// Typically one of the last items to configure.
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "App", action = "Index" }
);
});
// Force synchronous call with Wait();
seeder.EnsureSeedData().Wait();
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
}
}
}