Asp.net webapi enum parameter with default value

前端 未结 3 1175
你的背包
你的背包 2021-02-14 02:44

I have a controller

   [HttpGet]
    [RoutePrefix(\"api/products/{productId}\")] 
    public HttpResponseMessage Products(int productId,TypeEnum ptype=TypeEnum.C         


        
3条回答
  •  别跟我提以往
    2021-02-14 03:30

    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.

提交回复
热议问题