Asp.net webapi enum parameter with default value

前端 未结 3 1191
你的背包
你的背包 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:46

    Defining all your enum parameters as strings and then parsing them everywhere means you have to do this on every single action and you will need to come up with a consistent approach such that all parsing errors conform.

    This is a parameter binding issue and should not be dealt with in the controller layer, it should be taken care of in the pipeline. One way to do this is to create a custom filter and add it to your config.

    public class ModelStateValidationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = 
            }
        }
    }
    

    And in your global.asax.cs

    ...
    GlobalConfiguration.Configure(WebApiConfig.Register);
    ...
    
    public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            ...
            config.Filters.Add(new ModelStateValidationAttribute());
            ...
        }
    }
    

    If you're having trouble with the model state, it's type is a ModelStateDictionary and you simply iterate over it and then it's Errors property contains all the model binding issues. e.g.

    modelState = actionContext.ModelState;
    modelState.ForEach(x =>
            {
                var state = x.Value;
                if (state.Errors.Any())
                {
                    foreach (var error in state.Errors)
                    {
                        
                    }
                }
            });
    

提交回复
热议问题