簡體   English   中英

如何將錯誤從ASP.Net Razor頁面中的API自動重定向到錯誤頁面?

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

我正在制作Razor Pages應用程序,並且正在使用HttpClientPageModel向某些API發出請求。 ApiClient基本上是從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
    }
  }
}

如果從API收到400 BadRequest或其他錯誤,如何設置自動重定向? 還是在發送請求時需要每次檢查?

我知道,我可以使用Redirect或其他功能,但是我想使其自動運行。

@編輯

沒關系,我的項目已經關閉。 無論如何,謝謝您的幫助!

對於HttpClient ,您無法在HttpClient內部重定向。 您只能在PageModel重定向。

要解決此問題,您可以嘗試在ApiClient.PostAsync引發Exception並使用app.UseExceptionHandler("/Error"); 重定向到錯誤頁面。

  1. 定義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. 注冊ApiClient

      services.AddScoped<ApiClient>(); 
  3. PageModel調用

      public class IndexModel : PageModel { private readonly ApiClient _apiClient; public IndexModel(ApiClient apiClient) { _apiClient = apiClient; } public async Task OnGet() { var result3 = await _apiClient.GetAsync("https://www.baidu.com/"); } 
  4. HttpClient實現您所需的方法,例如PostAsync

您可以對所有響應代碼(如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
      }
    }

它與Razor Pages不兼容,因為坦率地說API與Razor Pages並不真正兼容。 但是,使用實際的控制器(和ASP.NET Core 2.1+),可以使用[ApiController]屬性裝飾它。 然后,ASP.NET Core將(除其他事項外)自動返回400,並將ModelState轉換為JSON,只要ModelState無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM