ASP.NET Core 中有一个常见的问题,即在使用 JSON 模型绑定时,当使用整数(int)表示枚举时,不能正确将其转换为枚举类型。这是因为默认情况下,JSON 模型绑定器只使用强命名程序集中的 EnumerationValueBinder 来绑定枚举的值,而没有考虑 int 类型绑定的情况。
为了解决这个问题,您需要自定义一个枚举值绑定器,专门用于将 int 值转换为枚举类型。这里提供一个简单的示例代码,可以在 Startup.cs 文件中添加如下配置来定义枚举绑定器:
using System;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
public class IntToEnumValueBinder : IModelBinder where T : struct
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
try
{
var value = (T)Enum.ToObject(typeof(T), Convert.ToInt32(valueProviderResult.FirstValue));
bindingContext.Result = ModelBindingResult.Success(value);
}
catch (Exception)
{
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
}
}
public class IntToEnumValueBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (!context.Metadata.IsEnumerableType && context.Metadata.ModelType.IsEnum)
{
return new IntToEnumValueBinder<>();
}
return null;
}
}
然后,在 Startup.cs 文件的 ConfigureServices 方法中添加以下代码,以注册自定义的枚举绑定器:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new IntToEnumValueBinderProvider());
});
}
现在,您就可以在您的代码中使用整数类型来表示枚举了,而且 JSON 模型绑定器也可以正确地将它们转换