[英]How to conditionally redirect to a page based on Radio Button Selection in ASP.NET Core Razor Pages?
[英]How to auto redirect errors from API in ASP.Net Razor Pages to error page?
我正在制作Razor Pages應用程序,並且正在使用HttpClient
從PageModel
向某些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");
重定向到錯誤頁面。
定義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); } }
注冊ApiClient
services.AddScoped<ApiClient>();
從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/"); }
從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.