2017-07-03 25 views
0

我有包含以下代碼的控制器的.NET核心ASP.NET web應用程序:ASP.NET Web App控制器,如何處理錯誤?

public async Task<IActionResult> Index(ConfigurationViewModel viewModel) 
    { 
     if (ModelState.IsValid) 
     { 
      // Update 
      var configurationClient = new ConfigurationClient(); 
      HttpResponseMessage response = await configurationClient.SetConfigurationValuesAsync(...); 
      if (!response.IsSuccessStatusCode) 
      { 
       // How to report back to user? 
      } 
     } 

     return View(viewModel); 
    } 

上面的代碼調用Web API,並且可以返回錯誤。

應該如何在代碼中處理這些錯誤?

回答

1

您可以通過模型狀態字典

if (ModelState.IsValid) 
{ 
    // your other code goes here 
    if (!response.IsSuccessStatusCode) 
    { 
    // to do : Log errors for you :) 
    ModelState.AddModelError(string.Empty,"Some error message");  
    } 
} 
return View(viewModel); 

發送一些錯誤信息假設您正在使用驗證標記輔助視圖呈現驗證錯誤信息給用戶

<form asp-action="Index" method="post">  

    <div asp-validation-summary="All"></div> 

    <!-- your input elements here --> 
    <input type="submit"/> 

</form> 
0

嗨,你可以像下面一樣使用

public async Task<IActionResult> Index(ConfigurationViewModel viewModel) 
    { 
     if (ModelState.IsValid) 
     { 
      // Update 
      var configurationClient = new ConfigurationClient(); 
      HttpResponseMessage response = await configurationClient.SetConfigurationValuesAsync(...); 
      if (!response.IsSuccessStatusCode) 
      { 
       // How to report back to user? 

        return View(viewModel); 
      } 
     } 

     return View(viewModel); 
    } 

Brief關於return視圖(viewModel):

通過此方法準備的結果對象在執行對象時由ASP.NET MVC框架寫入響應。

+0

您提供的代碼中是否缺少某些內容?我無法看到任何報告任何錯誤。 – OlavT

+0

yup裏面的if(!response.IsSuccessStatusCode)如果你只是返回視圖與視圖模型然後modelstate錯誤將自動顯示在視圖中使用驗證標籤 –

+0

是的,但錯誤不是由於驗證錯誤。這是從HTTP請求返回的錯誤代碼。 – OlavT