- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProgram.cs
98 lines (79 loc) · 2.87 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
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
usingMicrosoft.AspNetCore.Mvc;
usingSystem.Net;
usingMicrosoft.AspNetCore.Mvc.ModelBinding;
usingMicrosoft.AspNetCore.Http.Extensions;
varbuilder=WebApplication.CreateBuilder();
builder.Services.AddControllersWithViews();
varapp=builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();
[ApiController]
publicclassHomeController:Controller
{
[HttpGet("")]
publicActionResult<string>Index()
{
try
{
thrownewApplicationException("Catch this one");
}
catch(Exceptionex)
{
returnthis.ApiProblemDetails(HttpStatusCode.InternalServerError,exception:ex);
}
}
}
publicclassApiProblemsDetails:ProblemDetails
{
publicstringRequestPath{get;set;}
publicobjectRequestPayload{get;set;}
publicIReadOnlyDictionary<string,string>ValidationMessages{get;set;}=newDictionary<string,string>();
publicstringStackTrace{get;set;}
}
publicstaticclassControllerExtensions
{
publicstaticActionResultApiProblemDetails(thisControllerself,HttpStatusCodestatusCode,
stringtitle="",
stringdetail="",
IReadOnlyDictionary<string,string>validationMessages=null,
ModelStateDictionarymodelState=null,
Exceptionexception=null,
objectrequest=null)
{
vardetails=newApiProblemsDetails
{
Title=title,
Detail=detail,
RequestPath=self.Request.GetDisplayUrl(),
Status=(int)statusCode
};
if(validationMessages!=null)
details.ValidationMessages=validationMessages;
if(modelState!=null)
{
varmodelStateMessages=modelState
.Where(x =>x.Value.Errors.Count>0)
.ToDictionary(
kvp =>kvp.Key,
kvp =>string.Join(",",kvp.Value.Errors.Select(e =>e.ErrorMessage).ToArray())
);
if(details.ValidationMessages==null)
details.ValidationMessages=modelStateMessages;
else
details.ValidationMessages=details.ValidationMessages.Union(modelStateMessages).ToDictionary(x =>x.Key, x =>x.Value);
}
varhost=self.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))asIWebHostEnvironment;
if(exception!=null&&host.EnvironmentName==Environments.Development)
{
if(string.IsNullOrWhiteSpace(details.Detail))
details.Detail="Exception Message: "+exception.Message;
else
details.Detail+="\n\n Exception Message: "+exception.Message;
details.StackTrace=exception.StackTrace;
}
if(request!=null)
details.RequestPayload=request;
returnself.StatusCode((int)statusCode,details);
}
}