I have the following action signature
[ValidateInput(false)]
public HttpResponseMessage PostParam(Param param)
With Param looking something like this:
public class Param {
public int Id { get; set;}
public string Name { get; set; }
public string Choices { get; set; }
}
Here's the hitch - what comes over the wire is something like this
{
Id: 2,
Name: "blah",
Choices: [
{
foo: "bar"
},
{
blah: "blo"
something: 123
}
]
}
I don't want "Choices" to deserialize - I want it stored as a string (yes, I understand the security implications). Understandably, I get an error because since the default binder does not know this.
Now with Asp Mvc creating a specific ModelBinder would be fairly simple. I'd
inherit DefaultModelBinder
override the property deserialization with my own
set the binder in my Application_Start using Binders.Add
Seems like with Web Api this is a different process - the System.Web.DefaultModelBinder doesn't have anything to override and that I can't hook things up using Binders.Add. I've tried looking around but couldn't find much on how to actually do what I want. This is further complicated since apparently the ModelBinders api changed quite a bit over Beta and RTM so there's a lot of outdated information out there.
In Web API you have to distinguish three concepts - ModelBinding, Formatters and ParameterBinding. That is quite confusing to people moving from/used to MVC, where we only talk about ModelBinding.
ModelBinding, contrary to MVC, is responsible only for pulling data out of URI. Formatters deal with reading the body, and ParameterBinding (HttpParameterBinding) encompasses both of the former concepts.
ParameterBinding is really only useful when you want to revolutionize the whole mechanism (i.e. allow two objects to be bound from body, implement MVC-style binding and so on) - for simpler tasks modifying binders (for URI specific data) or formatters (for body data) is almost always more than enough.
Anyway, to the point - what you want to achieve can very easily be done with a custom JSON.NET converter (JSON.NET is the default serialization library behind Web API JSON formatting engine).
All you need to do is:
public class Param
{
public int Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(CustomArrayConverter))]
public string Choices { get; set; }
}
And then add the converter:
internal class CustomArrayConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var array = JArray.Load(reader);
return JsonConvert.SerializeObject(array);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, JArray.Parse(value as string));
}
}
In this case we are telling JSON.NET in the converter to store Choices as string (in the read method), and when you return the Param object with the Choices property to the client (in the write method) we take the string and serialize to an array so that the output JSON looks identical to the input one.
You can test it now like this:
public Param PostParam(Param param)
{
return param;
}
And verify that the data coming in is like you wished, and the data coming out is identical to the original JSON.
Related
In our ASP.net Core Web API application I am looking for a way to catch binding errors when my controller method accepts a complex object which has an ENUM property when ENUMs are de/serialized as strings.
eg.
class Person
{
public string Name {get; set;}
public SexEnum Sex {get; set;}
}
enum SexEnum
{
Male,
Female,
Other
}
We use system wide StringEnumConverter so a JSON serialized instance of Person looks like so:
{
"name": "Ann",
"sex": "female"
}
Now if I post this JSON (note the typo in the sex property):
{
"name": "Ann",
"sex": "femal"
}
the whole object received by the controller method is NULL as binding failed.
I would like to catch that binding error and, instead of having the pipeline go into the controller as if nothing is wrong, return a BAD REQUEST to the client including the detail of which property value failed to bind.
I know the type I am trying to deserialize into, I know the property type I am trying to deserialize and I can see the value does not parse into the type. So I think there must be a way of providing that detail to the client. I just don't know where and how to plug this in.
I would like the solution to be system wide so that all enums are covered, without having to put attributes on the properties of the model or on the enums themselves. (This is because we distribute our API models as a nuget package which cannot have any dependencies.)
We had this issue recently and wrote our own attribute to handle it:
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($"{value} is not a valid value for type {enumType.Name}");
}
return ValidationResult.Success;
}
}
class Person
{
public string Name {get; set;}
[ValidEnumValue]
public SexEnum Sex {get; set;}
}
The error is then added to the ModelState so you can use ModelState.IsValid to check if the values are valid.
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
EDIT
If you don't want to use an attribute then you can derive a new converter from NewtonSoft StringEnumConverter and have that check the value is valid before reading the json e.g.
public class validEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(!Enum.IsDefined(objectType, reader.Value))
{
throw new ArgumentException("Invalid enum value");
}
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
This is added to the JsonOptions in your startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new validEnumConverter());
});
}
Following up on Simply Ged's answer above, AFAICS, this actually cannot be done as the model binding exceptions are swallowed (https://github.com/aspnet/Mvc/issues/3898)
ModelState contains model binding errors and you can get some information out of that. As we currently use only JSON serialization, I ended up implementing a filter to check the ModelState errors for JsonSerializationException. It is not perfect though as eg. to get the requested value (that failed the binding) out of the JsonSerializationException you need to parse the inner exception message.
If someone finds a better solution, I will be happy to hear.
Expanding on #Simply Ged's excellent answer, 2nd part, using a nullable enum produces System.ArgumentException: 'Type provided must be an Enum.' exception. An extra step is required to handle nullable enum, or a null value for the enum:
public class validEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type enumType = (Nullable.GetUnderlyingType(objectType) ?? objectType);
if(!Enum.IsDefined(enumType, reader.Value ?? string.Empty))
{
throw new ArgumentException("Invalid enum value");
}
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
Just got this issue recently.
The way I overcome that was applying
[EnumDataType(typeof(YOUR_ENUM_TYPE))] above your model enum.
Example:
public class SaladModel
{
[EnumDataType(typeof(SauceTypeEnum))]
public SauceTypeEnum SauceType { get; set; }
}
Now once you post this to the WebAPI endpoint, its validated and returns as BadRequest by the framework.
You do this with the JsonStringEnumConverter converter.
public class PersonModel
{
public string Name { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public SexKind Sex { get; set; }
}
public enum SexKind
{
Male,
Female,
Confused
}
I want to add an action to my OData controller. I'll be calling this action with the request body matching the following structure, and with the following validation requirements:
public class PublishModel
{
[Required, EnumDataType(typeof(JobEventType))]
public JobEventType Type { get; set; }
[Required, StringLength(100)]
public string ExternalRef { get; set; }
public DateTimeOffset? DateTime { get; set; }
}
With a normal ApiController, I'd normally have my controller method simply take an argument of this type, and it'd work. With OData, it seems I have to implement my method using a ODataActionParameters argument.
I can't figure out how I'm supposed to tell OData that the body of the request should match the above. The closest I've got is to have it expect it in a parameter:
var pa = mb.EntityType<Edm.JobEvent>().Collection.Action("publish");
pa.ReturnsFromEntitySet<Edm.JobEvent>("jobevent");
pa.Parameter<PublishModel>("evt");
But this requires me to send
{"evt":{"type":"...","externalRef":"...","dateTime":"..."}}
When what I want to send is just
{"type":"...","externalRef":"...","dateTime":"..."}
I understand that I can just specify the properties of my class as individual parameters, but that'll be harder to maintain and I'll lose the data annotation validation. Is there a way to handle this?
Consider the following model which uses XmlSerializer and JSON.net to serialize the object to and from the respective formats.
[XmlRoot("my_model")]
[JsonObject("my_model")]
public class MyModel {
[JsonProperty("property1")]
[XmlElement("property1")]
public string Property1 { get; set; }
[JsonProperty("important")]
[XmlElement("important")]
public string IsReallyImportant { get; set; }
}
Now consider the following ASP.NET MVC 3 action that accept JSON or XML requests and returns model in the respective format (based on the accept header).
public class MyController {
public ActionResult Post(MyModel model) {
// process model
string acceptType = Request.AcceptTypes[0];
int index = acceptType.IndexOf(';');
if (index > 0)
{
acceptType = item.Substring(0, index);
}
switch(acceptType) {
case "application/xml":
case "text/xml":
return new XmlResult(model);
case "application/json":
return new JsonNetResult(model);
default:
return View();
}
}
}
Custom ValueProviderFactory implementations exist for JSON and XML inputs. As it stands the IsReallyImportant is being ignored when the input is being mapped to MyModel. However, if I define the attributes of IsReallyImportant to use "isreallyimportant", then information is correctly serialized.
[JsonProperty("isreallyimportant")]
[XmlElement("isreallyimportant")]
public string IsReallyImportant { get; set; }
As expected the default binder uses the property name when mapping incoming values to the model. I had a look at the BindAttribute, however its not supported on properties.
How does one tell ASP.NET MVC 3 that the property IsReallyImportant should be bound to "important" in the incoming request?
I have too many models to write a custom binder for each. Note that I don't use ASP.NET Web API.
You can do only one custom ModelBinder which will look for JSonProperty and XMLElement attributes to map the right properties. This way you could use it everywhere and you won't have to develop a modelbinder for each model. Unfortunately, there is no other option to modify the property bindings than custom modelbinders.
I am building an application using MVC3, Razor view engine, Repository Pattern with Unit of Work and using EF4.1 Code First to define my data model.
Here is a bit of background (gloss over it if you want).
The application itself is just an Intranet 'Menu'.
The 2 main entities are MenuItem and Department of which:
MenuItem can have many Departments
Departments can have many MenuItems
MenuItem may have a MenuItem as a parent
This is how I have defined my Entities
public class MenuItem
{
public int MenuItemId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public virtual ICollection<Department> Departments { get; set; }
public int? ParentId { get; set; }
public virtual MenuItem ParentMenuItem { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
I am using the FluentAPI to define the Self Reference Many-to-Many for the MenuItem.
The issue I am having is passing a MenuItem to the view via JSON.
The central issues are that I have a circular reference between my entities that the built in JSON parser can't deal with and I have lazy loading and proxy generation still enabled.
I am using JSON.net library from Nuget as my JSON Serializer as this seems to be a nice way round the circular reference issue. I now am unsure how to 'fix' the proxy generation issue. Currently the serializer throws The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.
Can anyone help me with this? If I turn off proxy generation, I am going to have a hell of a time loading all of the MenuItem children so I am keen leave this on. I have read a fair amount and there seems to be a variety of different answers including projecting the entities into another object and serialize that, etc, etc. Ideally there would be some way of configuring JSON.net to ignore the RelationshipManager object?
Update
Here is what I have used as a Custom ContractResolver for JSON.Net serializer. This seems to have sorted out my issue.
public class ContractResolver : DefaultContractResolver
{
private static readonly IEnumerable<Type> Types = GetEntityTypes();
private static IEnumerable<Type> GetEntityTypes()
{
var assembly = Assembly.GetAssembly(typeof (IEntity));
var types = assembly.GetTypes().Where(t => String.Equals(t.Namespace, "Namespace", StringComparison.Ordinal));
return types;
}
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
if (!AllowType(objectType))
return new List<MemberInfo>();
var members = base.GetSerializableMembers(objectType);
members.RemoveAll(memberInfo => (IsMemberEntityWrapper(memberInfo)));
return members;
}
private static bool AllowType(Type objectType)
{
return Types.Contains(objectType) || Types.Contains(objectType.BaseType);
}
private static bool IsMemberEntityWrapper(MemberInfo memberInfo)
{
return memberInfo.Name == "_entityWrapper";
}
}
IEntity is an interface all my Code First entity objects implement.
I realise this question has an accepted answer, but I thought I would post my EF Code First solution for future viewers. I was able to get around the error message with the contract resolver below:
class ContractResolver : DefaultContractResolver
{
protected override List<System.Reflection.MemberInfo> GetSerializableMembers(Type objectType)
{
if (objectType.Namespace.StartsWith("System.Data.Entity.Dynamic"))
{
return base.GetSerializableMembers(objectType.BaseType);
}
return base.GetSerializableMembers(objectType);
}
}
This works because EF Code First classes inherit from the POCO class that you actually want serialized, so if we can identify when we are looking at an EF generated class (by checking the namespace) we are able to just serialize using the properties from the base class, and therefore only serialize the POCO properties that we were really after in the first place.
Well, you used powerful serialization API which serializes references and all members as well and now you complains that it serializes all members :)
I didn't test it but I believe this will bring you close to the solution.
JSON.NET is quite powerful tool and it should offer you the extensibility point to avoid this behavior but you will have to code it yourselves. You will need custom DataContractResolver where you define which members should be serialized. Here is the similar example for NHibernate.
You can implement some logic which will take only members present in the parent class of dynamic proxy. I hope this will not break lazy loading. To validate that current entity is proxy you can use this code to get all known proxy types:
IEnumerable<Type> types = ((IObjectContextAdapter)dbContext).ObjectContext.GetKnownProxyTypes();
Is it possible to use the selfvalidation attribute with my validations located in a metadatatype? I'm using Enterprise Library 5's Validation Application Block.
As I explained in my other answer, this isn't supported out of the box. However, this can be achieved by hooking into the framework using depedency injection and replace the existing AttributeValidatorFactory implementation. I written a post on my weblog on how to do this: Mixing Validation Application Block With DataAnnotation: What About SelfValidation?
I hope this helps.
This is currently not supported (out of the box) by VAB. Look for instance at this thread at the EntLib forum. I think the main reason this is not supported is because you can't simply place the [SelfValidation] method on the meta data type and expect this to work. Reason it won't work is because self validation methods will typically validate instance members of the type. The signature of the self validation method does not contain the actual object to validate.
A simple work around is call into the meta data type from the entity. For instance:
[MetadataType(typeof(InvoiceMetaData))]
[HasSelfValidation]
public partial class Invoice
{
public string Name{ get; set; }
public int Price { get; set; }
[SelfValidation]
public void CustomValidate(ValidationResults results)
{
// Call into the meta data class
InvoiceMetaData.Validate(this, results);
}
}
public class InvoiceMetaData
{
[StringLengthValidator(1, 10, Tag = "Name")]
string Name { get; set; }
[RangeValidator(0, RangeBoundaryType.Inclusive, 0,
RangeBoundaryType.Ignore, Tag = "Price")]
int Price { get; set; }
public static void CustomValidate(Invoice instance,
ValidationResults results)
{
results.AddResult(new ValidationResult("ErrorMessage1",
instance, "", "", null));
}
}
This of course isn't a very clean solution. VAB however is very extendable and version 5.0 only got better. If you want you can swap existing AttributeValidationFactory and replace it with a version that is able to do this. It won't be easy though.
Cheers