C# 验证Web api 2对象参数中的枚举
假设您向控制器发送一个类实例,并且该类具有枚举类型的属性C# 验证Web api 2对象参数中的枚举,c#,validation,asp.net-web-api,asp.net-web-api2,C#,Validation,Asp.net Web Api,Asp.net Web Api2,假设您向控制器发送一个类实例,并且该类具有枚举类型的属性 public class CoffeeController : ApiController { [HttpPost] public async Task<IHttpActionResult> OrderAsync(Order request) { return Ok(); } } public enum CoffeeType { Latte, Mocha,
public class CoffeeController : ApiController
{
[HttpPost]
public async Task<IHttpActionResult> OrderAsync(Order request)
{
return Ok();
}
}
public enum CoffeeType
{
Latte,
Mocha,
Espresso
}
public class Order
{
public CoffeeType Type { get; set; }
public string Name { get; set; }
}
我觉得这很奇怪。
为什么使用这种行为
是否有一种优雅的方法抛出错误?之所以这样做,是因为枚举基于整数类型,因此它们总是有一个值(值类型不能为null),并且默认为0。使用以下解决方法
public enum CoffeeType
{
Invalid = 0
Latte = 1,
Mocha = 2,
Espresso = 3
}
对模型应用验证。创建一个
ActionFilterAttribute
,并将其连接到管道中或用它装饰端点。建议您也考虑作为一个伟大的图书馆来执行验证。
请参阅中的示例以了解一个很好的示例。正如Brett所写,您可以使用ModelState.IsValid,ModelState将出现错误。 如果需要抛出错误,您可以为您的类型使用自定义媒体格式化程序,如:
public class OrderJsonFormatter : BufferedMediaTypeFormatter
{
public OrderJsonFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
public override bool CanReadType(Type type)
{
var canRead = type == typeof(Order);
return canRead;
}
public override bool CanWriteType(Type type)
{
return false;
}
public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return this.ReadFromStream(type, readStream, content, formatterLogger, CancellationToken.None);
}
public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
{
using (var reader = new StreamReader(readStream))
{
using (var jsonReader = new JsonTextReader(reader))
{
var jsonSerializer = new JsonSerializer();
if (type == typeof(Order))
{
try
{
var entity = jsonSerializer.Deserialize<Order>(jsonReader);
return entity;
}
catch (Exception ex)
{
//log error here
throw;
}
}
return null;
}
}
}
}
public class OrderJsonFormatter : BufferedMediaTypeFormatter
{
public OrderJsonFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
public override bool CanReadType(Type type)
{
var canRead = type == typeof(Order);
return canRead;
}
public override bool CanWriteType(Type type)
{
return false;
}
public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return this.ReadFromStream(type, readStream, content, formatterLogger, CancellationToken.None);
}
public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
{
using (var reader = new StreamReader(readStream))
{
using (var jsonReader = new JsonTextReader(reader))
{
var jsonSerializer = new JsonSerializer();
if (type == typeof(Order))
{
try
{
var entity = jsonSerializer.Deserialize<Order>(jsonReader);
return entity;
}
catch (Exception ex)
{
//log error here
throw;
}
}
return null;
}
}
}
}
GlobalConfiguration.Configuration.Formatters.Insert(0, new OrderJsonFormatter());