【问题标题】:Display custom error message in ASP .Net 5, MVC 6在 ASP .Net 5、MVC 6 中显示自定义错误消息
【发布时间】:2016-01-18 12:17:57
【问题描述】:

我有一种方法是调用 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();
}

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

谢谢

【问题讨论】:

  • 你的意思是像 Response.Write(Msg); ?
  • 是的,只是这样,但在 ASP.Net 5 中不支持。还有其他方法吗?

标签: c# model-view-controller asp.net-core asp.net-core-mvc


【解决方案1】:

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

1) 使用可以存储 List&lt;string&gt; Errors 的 ViewModel,您可以将其传递回您的视图。尽管对所有视图都这样做会非常重复且不易维护。

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

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

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

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

完整示例:

Notification.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
}

```

BaseController.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");
        }
    }

Layout.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;
        }
    }
}

【讨论】:

  • 嘿,你能提供第三个解决方案的任何工作示例吗??
  • 我已扩展示例以显示您需要添加的类和枚举。剩下的唯一事情就是将 CSS/JS 包含添加到 toastr.js 的视图中。
  • 很好的答案有很大帮助 - 但我有一个问题 - 如果你返回 View(model) - 有错误 - 方法 OnActionExecuting 没有被触发 - 如何修复它?谢谢
  • 我不确定我是否完全关注你 - 你是什么意思返回 View() 错误?您是说在返回 View 之前代码中的某处引发了异常吗?
【解决方案2】:

您可以在代码隐藏和 .ASPX 页面上使用 Response.Write(str)

<%
Response.Write(str)
%>

在代码隐藏中使用 Response.Write() 会将字符串放在页面的 HTML 之前,因此它并不总是有用。

您还可以在 ASPX 页面的某处创建服务器控件,例如标签或文字,并在代码隐藏中设置该控件的文本或值:

.ASPX:

<asp:Label id="lblText" runat="server" />

代码隐藏:

lblText.Text = "Hello world"

HTML 输出:

<span id="lblText">Hello World</span>

如果您不想添加 s,请使用文字:

<asp:Literal id="litText" runat="server" />

并设置文字的value属性而不是text属性:

litText.Value = "Hello World"

【讨论】:

  • 我没有 aspx 页面。查看页面为.cshtml页面
  • 建议你关注a tutorial
猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
相关资源
最近更新 更多