我有一个ASP.NET网络应用程序运行在一个Azure应用服务。
在进行了分析器跟踪之后,我注意到了以下三个.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异常?
当我在本地运行应用程序并通过Asc和Desc时,不会抛出任何异常,在Debug窗口中也看不到任何异常。
发布于 2022-11-07 13:05:00
默认情况下,绑定Enum需要与该值相对应的整数值。
如果您想提供一个string值,您必须通过向Enum类型声明添加一个属性来告诉模型绑定器,如下所示:
[ModelBinder(BinderType = typeof(EnumModelBinder))]
public enum SortOrder
{
}也可以在模型中向属性添加属性,如下所示:
[BindProperty(BinderType = typeof(EnumModelBinder))]
public SortOrder MySortOrder {get;set;}现在,模型绑定应该能够处理字符串。当然,字符串必须与枚举值完全匹配。
BTW:失败的Modelbinding不会抛出异常,它只是忽略了值,这意味着属性将获得它们的默认值。
发布于 2022-11-07 12:42:35
我已复制并能够解决,请遵循以下步骤
下面的

ActionModel.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; }
}
}ActionType.cs
namespace MVC_Sort
{
public enum ActionType
{
MMM = 1,
RRR = 2,
AAA = 3,
JJJ = 4,
EEE = 5,
SSS = 6,
HHH = 7
}
}ActionTypeModel.cs
视图中的
中的Enum值和标签名称。
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中的操作方法在请求时执行
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页面
model MVC_Sort.ActionModel
@{
ViewBag.Title = "Index";
}
@Html.LabelFor(model=>model.ActionId)
@Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)Extension.cs
它用于从ActionType获取或检索Enum值。
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);
}
}
}

https://stackoverflow.com/questions/74328096
复制相似问题