C# 具有默认值的Asp.net webapi枚举参数
我有一个控制器C# 具有默认值的Asp.net webapi枚举参数,c#,asp.net-web-api,enums,C#,Asp.net Web Api,Enums,我有一个控制器 [HttpGet] [RoutePrefix("api/products/{productId}")] public HttpResponseMessage Products(int productId,TypeEnum ptype=TypeEnum.Clothes) { if(!Enum.IsDefined(typeOf(TypeEnum),ptype)) //throw bad request exception else
[HttpGet]
[RoutePrefix("api/products/{productId}")]
public HttpResponseMessage Products(int productId,TypeEnum ptype=TypeEnum.Clothes)
{
if(!Enum.IsDefined(typeOf(TypeEnum),ptype))
//throw bad request exception
else
//continue processing
}
Myenum声明为
public TypeEnum
{
Clothes,
Toys,
Electronics
}
当前,如果某个垃圾值被传递,它将被转换为默认值。
我想做的是,如果我以api/products/1的形式调用控制器,那么应该为ptype分配默认值,即cloth。如果我以api/products/1?pType=somegarbagevalue的形式调用控制器,那么控制器应该抛出错误的请求异常。如何实现这一点?您必须使用
string
并使用TryParse()
将字符串转换为Enum
值
public HttpResponseMessage Products(int productId,string ptype="Clothes")
{
TypeEnum category = TypeEnum.Clothes;
if(!Enum.TryParse(ptype, true, out category))
//throw bad request exception if you want. but it is fine to pass-through as default Cloathes value.
else
//continue processing
}
这可能看起来很幼稚,但这种方法的好处是允许
ptype
参数用于任何字符串,并在ptype
无法绑定值时毫无例外地执行该过程。将所有枚举参数定义为字符串,然后到处解析它们意味着您必须在每个操作上执行此操作,并且将需要提出一致的方法,以便所有解析错误都一致
这是一个参数绑定问题,不应该在控制器层处理,应该在管道中处理。一种方法是创建一个自定义过滤器并将其添加到配置中
public class ModelStateValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = <your standardised error response>
}
}
}
如果您在模型状态方面遇到问题,那么它的类型是ModelStateDictionary,您只需对其进行迭代,然后它的Errors属性就包含所有模型绑定问题。e、 g
modelState = actionContext.ModelState;
modelState.ForEach(x =>
{
var state = x.Value;
if (state.Errors.Any())
{
foreach (var error in state.Errors)
{
<work your magic>
}
}
});
modelState=actionContext.modelState;
modelState.ForEach(x=>
{
var状态=x.值;
if(state.Errors.Any())
{
foreach(状态为.Errors的变量错误)
{
}
}
});
此类验证应在管道中处理,而不是在控制器中处理
public abstract class ETagMatchAttribute : ParameterBindingAttribute
{
private ETagMatch _match;
public ETagMatchAttribute(ETagMatch match)
{
_match = match;
}
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
if (parameter.ParameterType == typeof(ETag))
{
return new ETagParameterBinding(parameter, _match);
}
return parameter.BindAsError("Wrong parameter type");
}
}
像这样的。有关详细说明,请参阅我不太了解此解决方案。您的代码在哪里使用/处理问题中的
TypeEnum
?我已经问了一个链接到你的。
public abstract class ETagMatchAttribute : ParameterBindingAttribute
{
private ETagMatch _match;
public ETagMatchAttribute(ETagMatch match)
{
_match = match;
}
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
if (parameter.ParameterType == typeof(ETag))
{
return new ETagParameterBinding(parameter, _match);
}
return parameter.BindAsError("Wrong parameter type");
}
}