首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在本地查看模型绑定异常

如何在本地查看模型绑定异常
EN

Stack Overflow用户
提问于 2022-11-05 13:27:54
回答 2查看 53关注 0票数 1

我有一个ASP.NET网络应用程序运行在一个Azure应用服务。

在进行了分析器跟踪之后,我注意到了以下三个.NET异常:

代码语言:javascript
复制
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.

它们都有这样的堆栈跟踪:

代码语言:javascript
复制
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

引起此问题的我的操作方法如下:

代码语言:javascript
复制
public async Task<IHttpActionResult> GetAsync(SortOrder sort = SortOrder.Ascending)
{
    // sort something
}

使用参数(如Asc )调用此操作方法。

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

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

当我在本地运行应用程序并通过AscDesc时,不会抛出任何异常,在Debug窗口中也看不到任何异常。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-11-07 13:05:00

默认情况下,绑定Enum需要与该值相对应的整数值。

如果您想提供一个string值,您必须通过向Enum类型声明添加一个属性来告诉模型绑定器,如下所示:

代码语言:javascript
复制
[ModelBinder(BinderType = typeof(EnumModelBinder))]
public enum SortOrder
{
}

也可以在模型中向属性添加属性,如下所示:

代码语言:javascript
复制
[BindProperty(BinderType = typeof(EnumModelBinder))]
public SortOrder MySortOrder {get;set;}

现在,模型绑定应该能够处理字符串。当然,字符串必须与枚举值完全匹配。

BTW:失败的Modelbinding不会抛出异常,它只是忽略了值,这意味着属性将获得它们的默认值。

票数 1
EN

Stack Overflow用户

发布于 2022-11-07 12:42:35

我已复制并能够解决,请遵循以下步骤

下面的

  • 是文件夹结构

ActionModel.cs

  • 将数据绑定到我们使用的操作模型

的视图。

代码语言:javascript
复制
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; }       
    }
}

ActionType.cs

  • 按排序顺序显示的Enum列表

代码语言:javascript
复制
namespace MVC_Sort
{
    public enum ActionType
    {
        MMM = 1,
        RRR = 2,
        AAA = 3,
        JJJ = 4,
        EEE = 5,
        SSS = 6,
        HHH = 7
    }

}

ActionTypeModel.cs

视图中的

  • 用于显示输出

中的Enum值和标签名称。

代码语言:javascript
复制
using System.ComponentModel.DataAnnotations;
namespace MVC_Sort
{
    public class ActionTypeModel
    {
        [Display(Name = "Names")]
        public int ActionId { get; set; }
        public ActionType ActionTypeList { get; set; }
    }
}

HomeController.cs

HomeController中的操作方法在请求时执行

代码语言:javascript
复制
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);
        }
    }
}

Index.cshtml

  • 是执行

时显示的Html页面

代码语言:javascript
复制
model MVC_Sort.ActionModel
@{
    ViewBag.Title = "Index";
}

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

Extension.cs

它用于从ActionType获取或检索Enum值。

代码语言:javascript
复制
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);
        }
    }
}

  • 在上述步骤之后单击debug => 开始调试。之后,它将按排序顺序在浏览器中打开下面的一个

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74328096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档