Constantly Receiving StatusText: "OK"
I recently configured HTTPS SSL certification for testing purposes, but I keep getting the "OK" status in StatusText. Ideally, it should return "Bad Request" or "Unauthorized"...etc. I would appreciate some assistance in understanding whether the error is in the startup class or in the Angular front-end.
API Controller Issue
[ApiController]
[Route("api/[controller]")]
public class BuggyController : BaseApiController
{
private readonly ApplicationContext __context;
public BuggyController(ApplicationContext _context)
{
__context = _context;
}
[Authorize]
[HttpGet("auth")]
public ActionResult<string> GetSecret()
{
return Ok("secret Text");
}
[HttpGet("not-found")]
public ActionResult<AppUser> GetNotFound()
{
var userIsExsists = __context.AppUsers.Find(-1);
if (userIsExsists == null) return NotFound();
return Ok(userIsExsists);
}
[HttpGet("server-error")]
public ActionResult<string> GetServerError()
{
var userIsExsists = __context.AppUsers.Find(-1);
var response = userIsExsists.ToString();
return response;
}
[HttpGet("bad-request")]
public ActionResult<string> GetBadRequest()
{
return BadRequest("This Request Is a Bad Request!");
}
}
.NET Custom Exception Middleware Class
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger<ExceptionMiddleware> logger;
private readonly IHostEnvironment env;
public ExceptionMiddleware(
RequestDelegate next,
ILogger<ExceptionMiddleware> logger,
IHostEnvironment env)
{
this.next = next;
this.logger = logger;
this.env = env;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
context.Response.ContentType = "Application/Json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var response = env.IsDevelopment()
? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace.ToString(),
Guid.NewGuid().ToString()) : new ApiException(context.Response.StatusCode, "Something Happend Wrong!");
var jsonOption = new JsonSerializerOptions{PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
var jsonResponse = JsonSerializer.Serialize(response, jsonOption);
await context.Response.WriteAsync(jsonResponse);
}
}
}
Utilization Of Custom Middleware
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ExceptionMiddleware>();
app.UseHttpsRedirection();
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
}
app.UseRouting();
app.UseCors(policy =>
policy.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("https://localhost:4200"));
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Angular Interceptor Class
@Injectable()
export class ErrorsInterceptor implements HttpInterceptor {
constructor(private route: Router, private toast: ToastrService) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
catchError((errorResponse) => {
if (errorResponse) {
switch (errorResponse.status) {
case 400:
if (errorResponse.error.errors) {
const modelStateErrors = [];
for (const key in errorResponse.error.errors) {
if (errorResponse.error.errors[key]) {
modelStateErrors.push(errorResponse.error.errors[key]);
}
}
throw modelStateErrors;
} else {
this.toast.error(errorResponse.statusText, errorResponse.status);
}
break;
case 401:
this.toast.error(errorResponse.statusText, errorResponse.status);
break;
case 404:
this.route.navigateByUrl("/not-found");
break;
case 500:
const navigationExtras: NavigationExtras = {
state: { error: errorResponse.error },
};
this.route.navigateByUrl("/server-error", navigationExtras);
break;
default:
this.toast.error("Something Unexpected Happened!");
console.log(errorResponse);
}
}
return throwError(errorResponse);
})
);
}
}
Calling API Endpoints
get404Error() {
this.http.get(this.baseUrl + "buggy/not-found").subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
get400Error() {
this.http.get(this.baseUrl + "buggy/bad-request").subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
get500Error() {
this.http.get(this.baseUrl + "buggy/server-error").subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
get401Error() {
this.http.get(this.baseUrl + "buggy/auth").subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
get400ValidationError() {
this.http.post(this.baseUrl + "Acccount/Register", { }).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}