Asp.net webapi枚举参数的默认值 [英] Asp.net webapi enum parameter with default value
问题描述
我有一个控制器
[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被声明为
Myenum is declared as
public TypeEnum
{
Clothes,
Toys,
Electronics
}
当前,如果传递了一些垃圾值,它将被转换为默认值。
我想做的是,如果我将控制器称为api / products / 1,则应该为ptype分配默认值,即衣服。如果我将控制器称为api / products / 1?pType = somegarbagevalue,则控制器应抛出错误的请求异常。我该如何实现?
Currently if,some garbage value is passed it is getting converted into default value. What I want to do is if i call the controller as api/products/1 then the ptype should be assigned default value i.e clothes. If I call the controller as api/products/1?pType=somegarbagevalue then the controller should throw bad request exception. How can I achieve this?
推荐答案
您必须使用 string
并使用 TryParse()
将字符串转换为 Enum
值。
You have to do with string
and use TryParse()
to convert string to Enum
value.
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
失败时无例外地执行处理绑定值。
It may look naive but the benefit of this approach is to allow ptype
parameter to whatever string and to perform process without exception when ptype
fails to bind the value.
这篇关于Asp.net webapi枚举参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!