简体   繁体   中英

Asp.net Core 3.0 Separate Global Exception Handling for WebApi and MVC (including Razor Pages)

I have a filter to check for exceptions and return errors in json objects for my webapi.

In the same project, I have Razor Pages and MVC pages when exceptions are thrown, will return json objects. How can I separate the two and use error pages for razor pages and MVC pages?

Thanks!

For separating exception handling for api and mvc, you could distinguish them by the request path, try something like below:

//use for mvc to return error page
app.UseDeveloperExceptionPage();
//use for api to return custom object
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), subApp =>
{
    subApp.UseExceptionHandler(builder =>
    {
        builder.Run(async context =>
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Error");
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM