How to auto redirect errors from API in ASP.Net Razor Pages to error page?

mvc 5 custom error page not working
redirect to error page from global.asax mvc core custom error page
custom error page in example core web api error handling middleware
404 error mvc routing
iexceptionhandlerpathfeature core 2.0 exception handling

I'm making Razor Pages app and I'm using HttpClient to make request from PageModel to some API. (ApiClient is basically class which derives from HttpClient

  public class IndexModel : MyPageModel {
    public IndexModel(ApiClient client) : base(client) { }

    public void OnGet() {
      var response = _client.PostAsync("account/login", new StringContent("")).Result;
      var status = response.StatusCode; // If status == BadRequest, redirect to Error.html

How can I set automatic redirect if I get 400 BadRequest or other error from API? Or do I need to check it every time, when I'm sending a request?

I know, that I can use Redirect or something, but I want to make it automatic.


Nevermind, my project was closed. Thanks for help anyways!

For HttpClient, you could not redirect inside HttpClient. You could only redirect in PageModel.

For a workaround, you could try throw Exception in ApiClient.PostAsync and use app.UseExceptionHandler("/Error"); to redirect to the error page.

  1. Define ApiClient

    public class ApiClient : HttpClient
    public Func<HttpResponseMessage, HttpResponseMessage> Action => (response) =>
        if (response.StatusCode != System.Net.HttpStatusCode.OK)
            throw new Exception(response.ToString());
        return response;
    public async Task<HttpResponseMessage> GetAsync(string requestUri)
        var result = await base.GetAsync(requestUri);
        return Action(result);
  2. Register ApiClient

  3. Call from PageModel

     public class IndexModel : PageModel
    private readonly ApiClient _apiClient;
    public IndexModel(ApiClient apiClient)
        _apiClient = apiClient;
    public async Task OnGet()
        var result3 = await _apiClient.GetAsync("");
  4. Implement your required method from HttpClient like PostAsync.

Custom error pages in ASP.NET MVC. Easy, right?, If you've ever struggled to configure custom error pages in ASP. to do this correctly, not helped by the fact that some errors are handled by ASP. NET's default behaviour of redirecting to the custom error page to rewrite the  Create ASP.NET Core Razor Pages Project On the Visual Studio, create new ASP.NET Core Web Application project Select Empty Template Click Ok button to Finish Configurations Open Startup.cs file and add new configurations as below: using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace

You can handle like this for all the response code except Ok (200)..

public void OnGet() {
      var response = _client.PostAsync("account/login", new StringContent("")).Result;
      var status = response.StatusCode;
      if(status != HttpStatusCode.OK){
          //redirect to error page

Handle errors in ASP.NET Core, This article covers common approaches to handling errors in ASP.NET The Razor Pages app template provides an Error page (.cshtml) and PageModel Redirects the client to the location provided in the URL template. is described in or  The ASP.NET team have included middleware for managing HTTP errors in the 400 and 500 ranges. It is called StatusCodePagesMiddleware , and is found in the Microsoft.AspNetCore.Diagnostics package . There are a number of extension methods for registering StatusCodePagesMiddleware as part of the pipeline in the Configure method of the Startup class.

It's not compatible with Razor Pages, because frankly APIs aren't really compatible with Razor Pages. However, with an actual controller (and ASP.NET Core 2.1+), you can decorate it with the [ApiController] attribute. ASP.NET Core, then, will (among other things) automatically return a 400 with ModelState converted to JSON whenever ModelState is invalid.

Displaying a Custom Error Page (C#), What does the user see when a runtime error occurs in an ASP. In a perfect world there would be no run-time errors. NET application one of three types of error pages is displayed: This is accomplished by specifying the URL of the error page in the <customErrors> section's defaultRedirect attribute. The key to managing the issue is understanding it. The kind of errors I'm discussing in this article fall into two distinct categories: runtime errors that result from assumptions you made in code that didn't cover all the bases; and ones that result from the unforeseen failure of dependencies.

Best Practices for Error Handling in ASP.NET MVC, ASP.NET provides several different ways to handle errors. Learn how to handle errors. In this article, we will review MVC error handling best practices. It works perfectly for tailoring specific error pages for a specific MVC controller or action method. Exception); //Redirect or return a view, but not both. This article covers common approaches to handling errors in ASP.NET Core web apps. See Handle errors in ASP.NET Core web APIs for web APIs. View or download sample code. ( How to download .) The article includes instructions about how to set preprocessor directives ( #if, #endif, #define) in the sample app to enable different scenarios.

How to Make Custom Error Pages Work in ASP.NET MVC 5, The HTML Action Link Helper class acts like the ASP.NET Link button and it will redirect the user to the mentioned page or the proper Controller  10 things to know about in-memory caching in ASP.NET Core: Consume ASP.NET Core Web API using HttpClient: Offline installation of VS2017 in 4 Easy Steps: Read and Write Cookies in ASP.NET Core 1.0: Form, Query String and HttpContext in ASP.NET Core 1.0: Seed Users and Roles Data in ASP.NET Core Identity: Use Razor Pages, MVC, and Web API in a

Web.config customErrors element with ASP.NET explained, NET and MVC using the customErrors element in your web.config file. NET/​MVC/Web API Web.config file, is something almost everyone uses somehow, NET MVC, I've used the custom errors element again and again. NET will automatically redirect the user to /Error?aspxerrorpath=/default.aspx . Razor Pages are derived from PageModel. By convention, the PageModel -derived class is called <PageName>Model. The constructor uses dependency injection to add the RazorPagesMovieContext to the page. All the scaffolded pages follow this pattern. See Asynchronous code for more information on asynchronous programming with Entity Framework.

  • First of all you need to create a controller method with return a error page with return Redirect("path");
  • So... it's not auto as I asked. I have to write if check every time... I know I can make simple if. But thanks for effort
  • From auto what you meant to achieve?
  • Auto check for errors in request like app.UseExceptionHandler("/Error"); It's redirecting to error page automatically, when Exception occurs
  • Thanks for answer. Hmm.. Can I override HttpClient and implement some Observator call (for example in HttpClient.GetAsync()) method, which will take care for redirecting or this all is just gibberish?
  • Maybe using HttpContext.Current.Response.Redirect?