-
Notifications
You must be signed in to change notification settings - Fork 399
/
Program.cs
74 lines (57 loc) · 1.99 KB
/
Program.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
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
using API.Models;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("*")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var connectionString = builder.Configuration.GetConnectionString("DB");
builder.Services.AddSqlServer<WaterConsumptionDb>(connectionString);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Water Consumption API", Description = "an API for Water Consumption", Version = "v1" });
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Water Consumption API V1");
});
app.MapGet("/hello", () => "hello");
app.MapGet("/hello2", () => "hello");
app.MapGet("/Consumption", ([FromHeader(Name = "dotnetconfstudentzone")] string ? key, WaterConsumptionDb db) => {
string ? secret = Environment.GetEnvironmentVariable("secret");
if (key == secret) {
return Results.Ok(db.WaterEntry.ToList());
} else {
return Results.StatusCode(401);
}
});
app.MapGet("/", () => "Hello World!");
app.MapPost("/Consumption", (
[FromHeader(Name = "dotnetconfstudentzone")] string ? key,
WaterEntry entry,
WaterConsumptionDb db ) => {
string ? secret = Environment.GetEnvironmentVariable("secret");
if (key == secret) {
int items = db.WaterEntry.Count();
entry.Id = items + 1;
db.WaterEntry.Add(entry);
db.SaveChanges();
return Results.Ok(entry);
} else {
return Results.StatusCode(401);
}
});
app.UseCors(MyAllowSpecificOrigins);
app.Run();