【问题标题】:How to view model binding exceptions locally如何在本地查看模型绑定异常
【发布时间】:2022-11-07 20:42:35
【问题描述】:

我有一个在 Azure 应用服务中运行的 ASP.NET Web 应用。

在进行探查器跟踪后,我注意到这三个 .NET 异常:

Requested value 'Asc' was not found.

Asc is not a valid value for SortOrder.

The parameter conversion from type 'System.String' to type 'Enums.SortOrder' failed. See the inner exception for more information.

他们都有这个堆栈跟踪:

mscorlib.ni![COLD] System.Enum+EnumResult.SetFailure
mscorlib.ni!System.Enum.Parse
system.ni!
system.web.http!System.Web.Http.ValueProviders.ValueProviderResult.ConvertSimpleType
system.web.http!System.Web.Http.ValueProviders.ValueProviderResult.UnwrapPossibleListType
system.web.http!System.Web.Http.ValueProviders.ValueProviderResult.ConvertTo
system.web.http!System.Web.Http.ModelBinding.Binders.TypeConverterModelBinder.BindModel
system.web.http!System.Web.Http.Controllers.HttpActionContextExtensions.Bind
system.web.http!System.Web.Http.ModelBinding.Binders.CompositeModelBinder.BindModel
system.web.http!System.Web.Http.ModelBinding.ModelBinderParameterBinding.ExecuteBindingAsync
system.web.http!System.Web.Http.Controllers.HttpActionBinding+<ExecuteBindingAsyncCore>d__12.MoveNext
mscorlib!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start
system.web.http!System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsyncCore
system.web.http!System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync
system.web.http!System.Web.Http.Controllers.ActionFilterResult+<ExecuteAsync>d__5.MoveNext
mscorlib!System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].Start
system.web.http!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync
system.web.http!System.Web.Http.ApiController.ExecuteAsync
system.web.http!System.Web.Http.Dispatcher.HttpControllerDispatcher+<SendAsync>d__15.MoveNext
mscorlib!System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon].Start
system.web.http!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync
system.net.http.ni!
system.web.http!System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync
system.net.http.ni!
autofac.integration.webapi!Autofac.Integration.WebApi.CurrentRequestHandler.SendAsync
system.net.http.ni!
Rend.invgen.invoicegateway.api!Rend.invgen.InvoiceGateway.Api.Handlers.RequestResponseLogHandler.SendNextAsync
Rend.invgen.invoicegateway.api!Rend.invgen.InvoiceGateway.Api.Handlers.RequestResponseLogHandler+<>c__DisplayClass0_0.<SendAsync>b__0
mscorlib.ni!System.Threading.Tasks.Task.Execute
mscorlib.ni!System.Threading.Tasks.Task.ExecutionContextCallback
mscorlib.ni!System.Threading.ExecutionContext.Run
mscorlib.ni!System.Threading.Tasks.Task.ExecuteWithThreadLocal
mscorlib.ni!System.Threading.Tasks.Task.ExecuteEntry
mscorlib.ni!System.Threading.Tasks.SynchronizationContextTaskScheduler.PostCallback
system.web.ni!
mscorlib.ni!System.Threading.Tasks.Task.Execute
mscorlib.ni!System.Threading.Tasks.Task.ExecutionContextCallback
mscorlib.ni!System.Threading.ExecutionContext.Run
mscorlib.ni!System.Threading.Tasks.Task.ExecuteWithThreadLocal
mscorlib.ni!System.Threading.Tasks.Task.ExecuteEntry
mscorlib.ni!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem
mscorlib.ni!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback

导致此问题的我的操作方法如下所示:

public async Task<IHttpActionResult> GetAsync(SortOrder sort = SortOrder.Ascending)
{
    // sort something
}

使用 Asc 等参数调用此操作方法。

尽管这似乎会导致 .NET 异常,但如果无法绑定值,则会使用默认值 Ascending

我的问题是,为什么我无法在本地查看 Requested value Asc was not found 异常?

当我在本地运行应用程序并传递AscDesc 时,没有抛出异常,并且在调试窗口中也看不到任何异常。

【问题讨论】:

  • 完全疯狂的猜测。但它是否与执行代码的操作系统有关。例如不同的底层 API 层?一个操作系统工作另一个错误?如果不是请无视我。
  • 事实证明没有异常,但是排序参数的 ModelState 对象中存在错误。

标签: c# .net azure azure-web-app-service asp.net-4.6


【解决方案1】:

我已经重现并能够解决,请按照以下步骤操作

  • 下面是文件夹结构

动作模型.cs

  • 要将数据绑定到我们使用动作模型的视图
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Mvc;

namespace MVC_Sort
{
    public class ActionModel
    {
        public ActionModel()
        {
            ActionsList = new List<SelectListItem>();
        }
        [Display(Name="Names")]
        public int ActionId { get; set; }

        public IEnumerable<SelectListItem> ActionsList { get; set; }       
    }
}

动作类型.cs

  • 按排序顺序显示的枚举列表
namespace MVC_Sort
{
    public enum ActionType
    {
        MMM = 1,
        RRR = 2,
        AAA = 3,
        JJJ = 4,
        EEE = 5,
        SSS = 6,
        HHH = 7
    }

}

ActionTypeModel.cs

  • 在视图中它用于在输出中显示枚举值和标签名称
using System.ComponentModel.DataAnnotations;
namespace MVC_Sort
{
    public class ActionTypeModel
    {
        [Display(Name = "Names")]
        public int ActionId { get; set; }
        public ActionType ActionTypeList { get; set; }
    }
}

家庭控制器.cs

  • 中的 Action 方法家庭控制器在请求时执行
namespace MVC_Sort.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ActionModel model = new ActionModel();
            IEnumerable<ActionType> actionTypes = Enum.GetValues(typeof(ActionType))
                                                       .Cast<ActionType>();

            var res= actionTypes.OrderBy(enm => enm.ToString()).ToArray();

            model.ActionsList = from action in res
                                select new SelectListItem
                                {
                                    Text = action.ToString(),
                                    Value = ((int)action).ToString()
                                };

            return View(model);
        }

        public ActionResult ActionTypes()
        {
            ActionTypeModel model = new ActionTypeModel();
            return View(model);
        }
    }
}

索引.cshtml

  • 执行时显示的Html页面
model MVC_Sort.ActionModel
@{
    ViewBag.Title = "Index";
}

@Html.LabelFor(model=>model.ActionId)
@Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)

扩展名.cs

  • 用于从动作类型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MVC_Sort
{
    public static class Extension
    {

        public static MvcHtmlString EnumDropDownListFor<TModel, TProperty, TEnum>(this HtmlHelper<TModel> htmlHelper,
                                                                                    Expression<Func<TModel, TProperty>> expression, 
                                                                                    TEnum selectedValue)
        {
            IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum))
                                        .Cast<TEnum>();

            IEnumerable<SelectListItem> items = from value in values
                                                select new SelectListItem()
                                                {
                                                    Text = value.ToString(),
                                                    Value = value.ToString(),
                                                    Selected = (value.Equals(selectedValue))
                                                };

            return SelectExtensions.DropDownListFor(htmlHelper,expression, items);
        }
    }
}
  • 以上步骤后点击调试=>开始调试.之后它将在浏览器中按排序顺序打开以下一个

【讨论】:

    猜你喜欢
    • 2012-08-27
    • 2016-12-28
    • 1970-01-01
    • 2013-05-19
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多