在 ASP .Net 5、MVC 6 中显示自定义错误消息

iDi*_*ipa 0 c# model-view-controller asp.net-core-mvc asp.net-core

我有一种方法是调用 api 方法。该 api 方法包含插入、更新、删除的 SQL 语句。但是当存储过程抛出任何错误时,如何在前面显示为错误消息。我正在使用 ASP .NET 5 和 MVC 6。我的方法如下:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Method(Model model)
{
    string url = ConfigurationSettingHelper.BaseUrl + "apiurl";

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.PostAsJsonAsync<Model>(url, model);

        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();
            var Msg = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(data);

            if (!string.IsNullOrEmpty(Convert.ToString(Msg)))
            {
                //Here code to display error message.
            }
        }
    }
    return View();
}
Run Code Online (Sandbox Code Playgroud)

帮助我在页面上显示 Msg 变量字符串消息。

谢谢你

Ian*_*uty 5

我认为有几种方法可以实现这一点。

1)使用可以存储List<string> Errors可以传递回视图的 ViewModel 。尽管对所有视图执行此操作将非常重复且不易维护。

2) 使用 TempData 来存储错误消息,而不是在您的 ViewModel 中。这样,您可以在 _Layout.cshtml 中检查 TempData 中是否有任何项目并以您希望的任何方式显示它们(这将发生在您的所有视图中)。

3) 使用 toastr.js 和 TempData 方法来显示一个不错的 toast。首先实现一个 POCO,它包括一个 Enum,用于 toastr.js 中可用的不同响应类型,即错误、信息、成功、警告。然后,创建您的控制器将实现的 BaseController.cs 文件,请参见下面的示例。

接下来在您的控制器中,您可以调用 CreateNotification(AlertType.Error, "This is a test message.", "Error");

最后,您需要将逻辑放入 _Layout.cshtml 文件中以使用通知。确保添加对 toastr.js 及其 CSS 文件的引用,并查看下面的示例以了解如何连接它:

完整示例:

通知.cs

``

public class Alert
{
    public AlertType Type { get; set; }
    public string Message { get; set; }
    public string Title { get; set; }
}

public enum AlertType
{
    Info,
    Success,
    Warning,
    Error
}
Run Code Online (Sandbox Code Playgroud)

``

基础控制器.cs

public override void OnActionExecuting(ActionExecutingContext context)
    {            
        GenerateNotifications();    

        base.OnActionExecuting(context);
    }

public void CreateNotification(Notification.AlertType type, string message, string title = "")
    {
        Notification.Alert toast = new Notification.Alert();
        toast.Type = type;
        toast.Message = message;
        toast.Title = title;

        List<Notification.Alert> alerts = new List<Notification.Alert>();

        if (this.TempData.ContainsKey("alert"))
        {
            alerts = JsonConvert.DeserializeObject<List<Notification.Alert>>(this.TempData["alert"].ToString());
            this.TempData.Remove("alert");
        }

        alerts.Add(toast);

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        };

        string alertJson = JsonConvert.SerializeObject(alerts, settings);

        this.TempData.Add("alert", alertJson);
    }

    public void GenerateNotifications()
    {
        if (this.TempData.ContainsKey("alert"))
        {               
            ViewBag.Notifications = this.TempData["alert"];
            this.TempData.Remove("alert");
        }
    }
Run Code Online (Sandbox Code Playgroud)

布局.cshtml

@if (ViewBag.Notifications != null)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    };
    List<Notification.Alert> obj = JsonConvert.DeserializeObject<List<Notification.Alert>>(ViewBag.Notifications, settings);

    foreach (Notification.Alert notification in obj)
    {
        switch (notification.Type)
        {
            case Notification.AlertType.Success:
                <script type="text/javascript">toastr.success('@notification.Message', '@notification.Title');</script>
                break;
            case Notification.AlertType.Error:
                <script type="text/javascript">toastr.error('@notification.Message', '@notification.Title');</script>
                break;
            case Notification.AlertType.Info:
                <script type="text/javascript">toastr.info('@notification.Message', '@notification.Title');</script>
                break;
            case Notification.AlertType.Warning:
                <script type="text/javascript">toastr.warning('@notification.Message', '@notification.Title');</script>
                break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我已经扩展了示例以显示您需要添加的 Class 和 Enum。剩下的唯一事情就是将 CSS/JS 包含添加到 toastr.js 的视图中。 (3认同)