简体   繁体   English

具有默认值的Asp.net webapi枚举参数

[英]Asp.net webapi enum parameter with default value

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 Myenum被宣布为

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 ie clothes. 我想要做的是如果我将控制器称为api / products / 1,那么应该为ptype指定默认值即衣服。 If I call the controller as api/products/1?pType=somegarbagevalue then the controller should throw bad request exception. 如果我将控制器称为api / products / 1?pType = somegarbagevalue,则控制器应抛出错误的请求异常。 How can I achieve this? 我怎样才能做到这一点?

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 = <your standardised error response>
        }
    }
}

And in your global.asax.cs 在你的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. 如果您遇到模型状态的问题,它的类型是ModelStateDictionary,您只需迭代它,然后它的Errors属性包含所有模型绑定问题。 eg 例如

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

You have to do with string and use TryParse() to convert string to Enum value. 您必须使用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
}

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. 它可能看起来很幼稚,但这种方法的好处是允许ptype参数为任何字符串,并且当ptype无法绑定值时执行过程无异常。

This type of validation should be handled in pipeline not in controller. 这种类型的验证应该在管道中而不是在控制器中处理。

    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");
    }
}

something like this. 这样的事情。 refer to MSDN link for detailed explanation 有关详细说明,请参阅MSDN链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM