Asp.net webapi enum parameter with default value
asp.net-web-api, c#, enums
Solution
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
}
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.
Problem
I have a controller ``` [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 is declared as ``` public TypeEnum { Clothes, Toys, Electronics } ``` 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?