-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartup.cs
More file actions
146 lines (128 loc) · 5.79 KB
/
Startup.cs
File metadata and controls
146 lines (128 loc) · 5.79 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Data;
using FoodTruckRodeo.API.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace FoodTruckRodeo.API
{
public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
// allows access to appsettings files
}
// 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)
{
// dependency injection container. when something needs to be consumed by another part of application it should be added as a service here for injection somewhere else in app
// add DataContext class as a service with (options)
// connecting to db , so need to specify
// database provider: sqlite
// connection string:
services.AddDbContext<DataContext>(db => db.UseSqlite(_config.GetConnectionString("DefaultConnection")));
// added NuGet package for Microsoft.AspNetCore.Mvc.NewtonsoftJson
// AddNewtonsoftJson() will act as if using .NET Core 2.2 with Newtonsoft JSON
services.AddControllers().AddNewtonsoftJson(
// Added this option to handle the error:
// fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
// An unhandled exception has occurred while executing the request.
// Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'menu' with type 'Models.Menu'. Path 'items[0]'.
opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
);
// make CORS service available to be used as middleware
services.AddCors();
// use AutoMapper to map between DTOs and Models. Give assembly where AutoMapper profiles will be defined.
services.AddAutoMapper(typeof(FoodTruckRepository).Assembly);
// instance of service is created once per scope
// <Interface, Implementation>
// Implementation can change at any point as long as signature of methods dont change in the Interface
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IFoodTruckRepository, FoodTruckRepository>();
// because we used [Authorize] attribute in Controller we need to add the service here with options
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// used to configure HTTP Request pipeline. as request comes in to API, request goes through this pipeline. this is middleware to interact with request through pipeline - ORDER MATTERS IN PIPELINE
if (env.IsDevelopment())
{
// if dev environment and there is an exception use dev friendly page to display
// global exception handler
app.UseDeveloperExceptionPage();
}
else
{
// Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline. The request will not be re-executed if the response has already started.
app.UseExceptionHandler(builder =>
{
// Adds a terminal middleware delegate to the application's request pipeline.
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
// store the error so it can be accessed
var error = context.Features.Get<IExceptionHandlerFeature>();
// if it's an actual error
if (error != null)
{
// use Extension to add messages to header
context.Response.AddApplicationError(error.Error.Message);
// write error message into HTTP Response
await context
// use an extension method to add custom errors to response
.Response.WriteAsync(error.Error.Message);
}
});
});
}
// redirect to https
// app.UseHttpsRedirection();
// use routing
app.UseRouting();
// use CORS
app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
// use authent
app.UseAuthentication(); // and add middleware here
app.UseAuthorization(); // to pipeline for [Authorize]
// use endpoints
app.UseEndpoints(endpoints =>
{
// map controller endpoints to app so api knows how to route requests
endpoints.MapControllers();
});
}
}
}