C# ASP.NET Web应用程序控制器,如何处理错误?

C# ASP.NET Web应用程序控制器,如何处理错误?,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个.NET核心ASP.NET web应用程序,其控制器包含以下代码: public async Task<IActionResult> Index(ConfigurationViewModel viewModel) { if (ModelState.IsValid) { // Update var configurationClient = new ConfigurationClie

我有一个.NET核心ASP.NET web应用程序,其控制器包含以下代码:

    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并可能返回错误


如何在代码中处理这些错误?

您可以通过模型状态字典发送一些错误消息

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>

嗨,你可以像下面这样使用

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);
    }
返回视图模型简介:


执行此对象时,ASP.NET MVC framework会将此方法准备的结果对象写入响应。

您提供的代码中是否缺少某些内容?我看不到报告任何错误的任何操作。是的,在if中!response.IsSuccessStatusCode如果仅返回带有viewmodel的视图,则modelstate错误将使用验证标记自动显示在视图中,但该错误不是由于验证错误引起的。这是HTTP请求返回的错误代码。