asp.net mvc 4 - MVC4 WebAPI reject invalid enum values -
how can make json.net / mvc 4 webapi reject integer values enum has no member? eg:
if have model:
public enum colour { red = 1 }; public class model { public colour colour { get; set; } } model post(model model) { // model.colour 99, 34234234, 0 etc, etc }
if post { color: 9999 }
, end model model.color = 999 , want return bad request status code instead.
one option write validator:
public class validenumvalueattribute : validationattribute { protected override validationresult isvalid(object value, validationcontext validationcontext) { type enumtype = value.gettype(); bool valid = enum.isdefined(enumtype, value); if (!valid) { return new validationresult(string.format("{0} not valid value type {1}", value, enumtype.name)); } return validationresult.success; } }
use as:
public enum color {red = 1, blue = 2} public class car { [validenumvalue] public color color { get; set; } }
in controller, modelstate.isvalid
false
.
can throw validationexception
, if want fail request, i'm not quite sure how should used.
Comments
Post a Comment