Reputation: 19
This is the function that I have in my startup.cs.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder =>
builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin());
app.UseMvc(routes =>
{
routes.MapRoute("apiActions", "api/{controller}/{action}");
});
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseMvcWithDefaultRoute();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
// FileProvider = new PhysicalFileProvider(
// Path.Combine(Directory.GetCurrentDirectory(), "Images")),
// RequestPath = new PathString("/Images")
});
}
What can I do to view an error in the response? I want the error to be emitted to the browser whenever I throw it in my controller.
So for example, if I do this:
[HttpGet]
public string GetStartUpURL(string gameID, int userId, string mode)
{
throw new Exception("Test");
return null;
}
I want an error to be returned instead of a blank body response with 500 code.
I am using a web api core, not mvc.
Upvotes: 1
Views: 1239
Reputation: 30056
For your issue, it is caused by that you are placing Error Handling
before UseMvc
. For catching error while this application, you should place Error Handling Middleware
on the first.
Try to modify your Configure
like below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseMvcWithDefaultRoute();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
// FileProvider = new PhysicalFileProvider(
// Path.Combine(Directory.GetCurrentDirectory(), "Images")),
// RequestPath = new PathString("/Images")
});
app.UseCors(builder =>
builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin());
app.UseMvc(routes =>
{
routes.MapRoute("apiActions", "api/{controller}/{action}");
});
}
If you want to custom the error reponse instead of using UseDeveloperExceptionPage
. You could try something like below:
app.UseExceptionHandler(
new ExceptionHandlerOptions
{
ExceptionHandler = async context =>
{
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error: {ex.Error.Message}</h1>";
await context.Response.WriteAsync(err);
}
}
});
Upvotes: 1