Serialize alternative property names from the form to POST

I am creating a callback endpoint for a third-party API. The caller will receive POST data with several forms.

Something like that:

public SomeApiController : ApiController { public AModel Post(AModel input) { return input; //for demonstration } } 

Some of the fields that he will place have a dash in the name, which cannot be the true name of the .NET property. So, I used [DataContract] and [DataMember (name = "blah")] to define serialization rules.

Model:

 //input model class [DataContract] public class AModel { [DataMember] public string NormalProperty {get; set;} //value set appropriately [DataMember(Name="abnormal-property")] public string AbnormalProperty {get; set;} //always null (not serializing) } 

With standard XML and JSON messages, this works great. Normal and AbnormalProperty are installed and I can carry my business.

However, with any variant of form data (form data, multipart / form-data, x-urlencoded-form-data, AbnormalProperty is incorrectly deserialized in the model and will always be null.

Is there a directive I'm missing or something else?

+5
source share
3 answers

After many beating of the head, we more or less made a combination of two things.

For URL-encoded forms, we followed

0
source

I tried your example, and my conclusion is that the DefaultModelBinder in ASP.NET MVC does not support this assignment of POST variables.

The obvious solution is not to use dashes in your names.

If this is not an option, you can implement your own connecting device for this particular model to handle the anomalous names that you send to your MVC controller. The following is an example of a custom mediation:

 public class AModelDataBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(AModel)) { var request = controllerContext.HttpContext.Request; string normal = request.Form.Get("normalproperty"); string abnormal = request.Form.Get("abnormal-property"); return new AModel { NormalProperty = normal, AbnormalProperty = abnormal }; } return base.BindModel(controllerContext, bindingContext); } } 

Then you will need to register this custom binder in Global.asax :

 ModelBinders.Binders.Add(typeof(AModel), new AModelDataBinder()); 

And finally, you can use a custom binder in your controller:

 [HttpPost] public ActionResult Index([ModelBinder(typeof(AModelDataBinder))]AModel input) { // Handle POST return View(); } 
+4
source

I think the main problem is that DataContract expecting raw data such as XML. What you are trying to do POST is HTML.

Types Supported by the Data Contract Serializer

+1
source

Source: https://habr.com/ru/post/1204983/


All Articles