AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs

319 lines
8.6 KiB
C#
Raw Permalink Normal View History

2022-09-27 11:25:53 +08:00
#define TEST_LAMBDA // MIDDLEWARE API_CONTROLLER API_CONT_SHORT DEFAULT DISABLE
2022-09-09 02:04:44 +08:00
#if NEVER
#elif MIDDLEWARE
2022-09-20 11:01:37 +08:00
// <snippet_middleware>
2022-09-09 02:04:44 +08:00
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
2022-09-23 11:26:52 +08:00
builder.Services.AddProblemDetails();
2022-09-09 02:04:44 +08:00
2022-09-23 11:26:52 +08:00
var app = builder.Build();
2022-09-09 02:04:44 +08:00
app.UseHttpsRedirection();
app.UseStatusCodePages();
2022-09-20 08:05:18 +08:00
// Middleware to handle writing problem details to the response.
2022-09-09 02:04:44 +08:00
app.Use(async (context, next) =>
{
2022-09-09 02:04:44 +08:00
await next(context);
var mathErrorFeature = context.Features.Get<MathErrorFeature>();
if (mathErrorFeature is not null)
{
if (context.RequestServices.GetService<IProblemDetailsService>() is
{ } problemDetailsService)
{
(string Detail, string Type) details = mathErrorFeature.MathError switch
{
MathErrorType.DivisionByZeroError => ("Divison by zero is not defined.",
"https://en.wikipedia.org/wiki/Division_by_zero"),
_ => ("Negative or complex numbers are not valid input.",
"https://en.wikipedia.org/wiki/Square_root")
};
await problemDetailsService.WriteAsync(new ProblemDetailsContext
{
HttpContext = context,
ProblemDetails =
{
2022-09-22 05:50:56 +08:00
Title = "Bad Input",
Detail = details.Detail,
Type = details.Type
}
});
}
}
2022-09-09 02:04:44 +08:00
});
// /divide?numerator=2&denominator=4
app.MapGet("/divide", (HttpContext context, double numerator, double denominator) =>
{
if (denominator == 0)
{
2022-09-20 09:34:09 +08:00
var errorType = new MathErrorFeature { MathError =
MathErrorType.DivisionByZeroError };
context.Features.Set(errorType);
2022-09-09 02:04:44 +08:00
return Results.BadRequest();
}
return Results.Ok(numerator / denominator);
2022-09-09 02:04:44 +08:00
});
// /squareroot?radicand=16
app.MapGet("/squareroot", (HttpContext context, double radicand) =>
2022-09-09 02:04:44 +08:00
{
if (radicand < 0)
{
2022-09-20 09:34:09 +08:00
var errorType = new MathErrorFeature { MathError =
MathErrorType.NegativeRadicandError };
context.Features.Set(errorType);
2022-09-09 02:04:44 +08:00
return Results.BadRequest();
}
return Results.Ok(Math.Sqrt(radicand));
2022-09-09 02:04:44 +08:00
});
app.MapControllers();
2022-09-09 02:04:44 +08:00
app.Run();
2022-09-20 11:01:37 +08:00
// </snippet_middleware>
#elif API_CONTROLLER
2022-09-20 09:53:13 +08:00
// <snippet_api_controller>
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails(options =>
options.CustomizeProblemDetails = (context) =>
{
var mathErrorFeature = context.HttpContext.Features
.Get<MathErrorFeature>();
if (mathErrorFeature is not null)
{
(string Detail, string Type) details = mathErrorFeature.MathError switch
{
MathErrorType.DivisionByZeroError =>
("Divison by zero is not defined.",
2022-09-20 09:53:13 +08:00
"https://wikipedia.org/wiki/Division_by_zero"),
_ => ("Negative or complex numbers are not valid input.",
2022-09-20 09:53:13 +08:00
"https://wikipedia.org/wiki/Square_root")
};
context.ProblemDetails.Type = details.Type;
2022-09-22 05:50:56 +08:00
context.ProblemDetails.Title = "Bad Input";
context.ProblemDetails.Detail = details.Detail;
}
}
);
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStatusCodePages();
app.UseAuthorization();
app.MapControllers();
2022-09-23 10:12:01 +08:00
app.Run();
// </snippet_api_controller>
#elif API_CONT_SHORT
// <snippet_apishort>
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapControllers();
app.Run();
// </snippet_apishort>
#elif DEFAULT
// <snippet_default>
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
// </snippet_default>
#elif MIN_API
// <snippet_min_api>
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails(options =>
options.CustomizeProblemDetails = (context) =>
{
var mathErrorFeature = context.HttpContext.Features
.Get<MathErrorFeature>();
if (mathErrorFeature is not null)
{
(string Detail, string Type) details = mathErrorFeature.MathError switch
{
MathErrorType.DivisionByZeroError =>
("Divison by zero is not defined.",
"https://wikipedia.org/wiki/Division_by_zero"),
_ => ("Negative or complex numbers are not valid input.",
"https://wikipedia.org/wiki/Square_root")
};
context.ProblemDetails.Type = details.Type;
context.ProblemDetails.Title = "Bad Input";
context.ProblemDetails.Detail = details.Detail;
}
}
);
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStatusCodePages();
app.UseAuthorization();
app.MapControllers();
2022-09-21 10:09:47 +08:00
// /divide?numerator=2&denominator=4
app.MapGet("/divide", (HttpContext context, double numerator, double denominator) =>
{
if (denominator == 0)
{
var errorType = new MathErrorFeature
{
MathError = MathErrorType.DivisionByZeroError
};
context.Features.Set(errorType);
return Results.BadRequest();
}
var calculation = numerator / denominator;
return Results.Ok(calculation);
});
// /squareroot?radicand=16
app.MapGet("/squareroot", (HttpContext context, double radicand) =>
{
if (radicand < 0)
{
var errorType = new MathErrorFeature
{
MathError = MathErrorType.NegativeRadicandError
};
context.Features.Set(errorType);
return Results.BadRequest();
}
return Results.Ok(Math.Sqrt(radicand));
});
app.Run();
2022-09-23 10:12:01 +08:00
// </snippet_min_api>
2022-09-23 10:42:19 +08:00
#elif DISABLE
// <snippet_disable>
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressMapClientErrors = true;
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
// </snippet_disable>
2022-09-27 11:25:53 +08:00
#elif TEST_LAMBDA
// <snippet_lambda>
2022-09-27 10:59:19 +08:00
using Microsoft.AspNetCore.Diagnostics;
using static System.Net.Mime.MediaTypeNames;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(exceptionHandlerApp =>
{
exceptionHandlerApp.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = Text.Plain;
var title = "Bad Input";
var detail = "Invalid input";
var type = "https://errors.example.com/badInput";
2022-09-27 10:59:19 +08:00
if (context.RequestServices.GetService<IProblemDetailsService>() is
{ } problemDetailsService)
{
var exceptionHandlerFeature =
context.Features.Get<IExceptionHandlerFeature>();
var exceptionType = exceptionHandlerFeature?.Error;
if (exceptionType != null &&
exceptionType.Message.Contains("infinity"))
{
title = "Arguement exception";
detail = "Invalid input";
type = "https://errors.example.com/arguementException";
}
2022-09-27 10:59:19 +08:00
await problemDetailsService.WriteAsync(new ProblemDetailsContext
{
HttpContext = context,
ProblemDetails =
{
Title = title,
Detail = detail,
Type = type
2022-09-27 10:59:19 +08:00
}
});
}
});
});
}
app.MapControllers();
app.Run();
// </snippet_lambda>
2022-09-09 02:04:44 +08:00
#endif