How to get controller to set ObjectId from posted JSON object - c#

I have a controller that adds or edits an entity which is sent to the controller as a JSON object.
Here is the controller:
public JsonResult SaveOrUpdateUser(User user)
{
Collection.Save(user);
//Collection is MongoDB.Driver.MongoCollection<User>
return Json(user);
}
If user is a new user, everything works perfectly. The mongo driver sets the ID like it should, and returns the new user with their ID set. However if the user is an existing user, and I'm updating something, mongo thinks it's a new user because MVC doesn't seem to be able to automatically set the ObjectId from the JSON I'm sending.
The JSON for an existing user looks like this (edited for brevity)
{
"Id": "5230d5c5eae61521585eda99",
"Username": "someone#domain.com",
"Password": "newpassword"
}
And the C# User class:
public class User
{
public ObjectId Id {get; set;}
public string Username {get; set;}
public string Password {get; set;}
}
However, user, when parsed by MVC, looks like this:
ObjectId Id = ObjectId(000000000000000000000000);
string Username = "someone#domain.com";
string Password = "newpassword";
As such, as far as the mongo driver is concerned, this is a new entity. So, is there a way to control how MVC parses the JSON into a User so that the ObjectId is properly set if it exists?

I've never had much luck using the default Model Binder for deserializing JSON. Try using Newtonsoft's library, I believe it is included with MVC 4 projects in Visual Studio 2012. If not you should be able to find it in the Nuget Package Manager.
You can either create a custom Model Binder for User and deserialize the object there or you could make the user parameter to you SaveOrUpdateUser a string instead and then do the deserialization there.
In either case the code is simply:
Newtonsoft.Json.JsonConvert.DeserializeObject<User>(jsonString)
Newtonsoft's JSON deserialization is pretty sophisticated and I was very impressed with how it just worked, even on deserializing some JSON into a custom object that had a Dictionary of another custom type as one of its properties. That being said, if it is not able to figure it out with the default configuration you can help it out by creating a custom JsonConverter. I have not done this myself so I will have to test out an example before I can provide guidance on that.

After some more searching, I found out how to handle this. I wanted to avoid manually deserializing the JSON object for each request (even if I had a generic factory method), and much preferred the object to be automatically bound by the controller.
The answer is to create a custom model binder that overrides BindModel() in System.Web.Mvc. Since this is an issue for any entity I have stored in Mongo, and not just the User class, my custom model binder needed to be generic so that I wouldn't have to create a largely redundant model binder for each entity I have.
Here is what this class looks like:
public class MongoEntityDataBinder<T> : DefaultModelBinder where T: IDataEntity
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string body;
using(var stream = controllerContext.HttpContext.Request.InputStream)
{
stream.Seek(0, SeekOrigin.Begin);
using(var reader = new StreamReader(stream))
{
body = reader.ReadToEnd();
}
}
if(string.IsNullOrEmpty(body)) return null;
try
{
return JsonConvert.DeserializeObject<T>(body);
}
catch(Exception)
{
return null;
}
}
}
Next, this custom model binder needs to be registered, so in Global.asax:
ModelBinders.Binders.Add(typeof(MongoEntityDataBinder<IDataEntity>), new MongoEntityDataBinder<IDataEntity>());
And finally, my controller now looks like this:
public JsonResult SaveOrEditUser([ModelBinder(typeof(MongoEntityDataBinder<User>))] User user)
{
//Function body
}
One final thing to note is that Json.NET doesn't inherently know how to serialize/deserialize ObjectId either, so I also needed to override Newtonsoft.Json.JsonConverter.WriteJson() and Newtonsoft.Json.JsonConverter.ReadJson() and then apply [JsonConverter(typeof(ObjectIdConverter))] to the Id property in IDataEntity
This article was an excellent starting point: ASP.NET Custom Model Binder

Related

What is the proper way to handle a generic object in a WEBAPI method?

The scenario is something like this:
I have this web-api which will handle a variety of payment gateways, and I want to have the same endpoint for all of those.
So, what I have in mind is to get some json data like this:
{
"OperationId":"N0004",
"Generic_Object_That_Will_Change_According_ToThe_GateWay":
{
"Sale_id":1000,
"CodUser":"1000040",
"Email":"teste#teste.com"
}
}
Or this, for some other payment gateway
{
"OperationId":"N044444",
"Generic_Object_That_Will_Change_According_ToThe_GateWay":
{
"Token":1000,
"UserSettings":{
id: "4563345",
name: "Average Joe"
}
}
}
What I want to do is to transform this "Generic_Object_That_Will_Change_According_ToThe_GateWay" in the specific object for each payment gateway (paypal, or some other), becase each one is completely different, but I don't want that to affect the way the client will call this API - I want it to be as flexible as possible, in a way that you just have to pass whatever data in this Generic_Object_That_Will_Change_According_ToThe_GateWay, and I will then cast it to the proper object and then call another endpoint(like an aggragate microservice design) passing this newly created object.
My idea so far, was creating some class with a generic property like this
public class Payment<Gateway>
{
public int OperationId{ get; set; }
public Gateway paymentGateWay{ get; set; }
}
And this property paymentGateWay could be typed according the available payment Gateways.
And then maybe I could get this data in the API method as Object, and do the necessary casts
[Route("api/payment")]
[HttpPost]
public string Compra(Object payment) {
But, to be honest, I don't know if I'm in the right way.
I already know that I can't have a generic method in a web-api endpoint - so what would be the correct way to get this data in my endpoint considering that a part of this json data is flexible/generic and may be cast to a few different objects.
To summarize, I want to handle json data that can be deserialized to a few different known objects, but I don't want to have a different method in my API to handle each one this possible data scenarios.
if you want a generic method in webapi you have to use JObject
something like the following
public void Post([FromBody] JObject testJObject)
{
//here you have to do some additional work in order to parse and get it working for generic entity
}
in addition to this, you can use the Schema validator against any received request and use the factory pattern in order to create the correct object
here an example
var json =
" {\"OperationId\":\"N0004\",\"Generic_Object_That_Will_Change_According_ToThe_GateWay\":{\"Sale_id\":1000,\"CodUser\":\"1000040\"}}";
JsonSchema paypalschema = new JsonSchema();
paypalschema.Type = JsonSchemaType.Object;
paypalschema.Properties = new Dictionary<string, JsonSchema>
{
{"OperationId", new JsonSchema {Type = JsonSchemaType.String}},
{
"Generic_Object_That_Will_Change_According_ToThe_GateWay",
new JsonSchema {Type = JsonSchemaType.Object,Properties = new Dictionary<string, JsonSchema>
{
{"Sale_id", new JsonSchema {Type = JsonSchemaType.Integer}},
{"CodUser", new JsonSchema {Type = JsonSchemaType.String}},
}}
}
};
JObject requestObject = JObject.Parse( json);
bool valid = requestObject.IsValid(paypalschema);
if (valid)
{
//create your GatewayObject here
}
//else check another gateway object
Consider using JObject or String as your input (And then converting to JObject.) Then you can do some type or data checking before casting. Here's an example shows how they use a pre-defined 'type' value provided, but in lieu of that, you can instead look in the JObject for the 'parts' of each unique provider's payload to determine which type to use.
You can have a generic controller to implement the method and instance-controllers, which inherit of the generic controller:
// I'll rename Gateway to TGateway according to the fact, that it is a generic Type parameter.
public class Payment<TGateway>
{
public int OperationId{ get; set; }
public TGateway paymentGateWay{ get; set; }
}
GenericController:
// Don't add a RouteAttribute to this Controller.
public class GenericController<TGateway>: ApiController
{
// The implementation of the method. No RouteAttribute.
[HttpPost]
public string Compra(Payment<TGateway> payment) {...}
}
InstanceController:
// No need to override the method. RouteAttribute.
[Route("api/payment/"+typeof(AGateway).Name)]
public class AGatewayController : GenericController<AGateway>
{}

JSON.NET - Ignore properties for serialization

I am currently developing a ASP.NET WebAPI using JSON.NET.
I am looking to reduce traffic and want to ignore certain properties of my models for serialization, i.e. I don't want to return them in my JSON response, but I want to accept them when they are passed to my endpoint.
Example class
public class User {
public int Id { get; set; }
public string Name { get; set; }
public string Role { get; set; }
}
Use-cases
I've got a POST endpoint that takes a User model as a parameter. The request contains Name and Role. Those props should be parsed into my User.
I've got a GET endpoint that returns a User. I only want the response to contain Id and Name. Role should be ignored.
Problem
When I use the JsonIgnore attribute from JSON.NET, the property is ignored entirely. It is not serialized for my response, but the prop of my User is null, when I post the JSON User to my endpoint.
Is there a way to ignore a prop only for serialization?
Thank you in advance!
That's exactly what Data Transfer Objects are for. You should create different DTOs for different purposes (GET/POST).
Use this and pass null when you want to ignore it!
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]

How do I use WebAPI/Rest correctly when other params are needed

I am new to WebAPI and rest and am trying to do things correctly. By default if I were to access something such as User I would call api/user/5 if I wanted user 5. This would go to my User controller to Get(int num) I think. But I know I will often need other params passed as well. Currently I have Get(JObject data), but that data param is for other parameters. I will need other optional params whether I am sending an ID or wanting a list of everything. How do I go about organizing methods properly with WebAPI? Am I misunderstanding something?
To clarify:
This question is more about REST than dynamic objects, though they play a part:
How do I get a single resource vs a list of resources when I need additional params. I see those concepts as two separate methods, but the additional params complicate it in my mind when routing is involved.
Use attribute routing
For example -
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
or
[Route("customers/{customerId}/orders/{orderId}")]
public Order GetOrderByCustomer(int customerId, int orderId) { ... }
if you need to return a list, create a method that returns a list, otherwise return the specific item requested
Look into using JToken or the even more dynamic 'dynamic' (Taken from here)
"
JSON and JavaScript is really dynamic, though, and often it's a hassle to try to "deserialize" really dynamic JSON objects into strongly-typed .NET structures. JSON.NET and ASP.NET Web API's model binding offer a happy medium - a middle ground - called JToken.
public class ContactController : ApiController
{
public JToken Post(JToken contact)
{
return contact;
}
}
Using JToken gives a dynamic container but also a DOM-like navigation model. But if that's not dynamic enough for me, why can't my method's parameter just take a "dynamic."
C# is statically typed, sure, but that doesn't mean I can't statically type something dynamic. ;)
Again, note the watch window.
Using dynamic to catch JSON post payloads
public class ContactController : ApiController
{
public dynamic Post(dynamic contact)
{
return contact;
}
}
"
I think you should make a new object for each WebAPI function that will handle the request. You can make the parameters optional with nullable properties.
[HttpPost]
public void SampleFunction(SampleFunctionModel model)
{
}
where SampleFunctionModel is:
public class SampleFunctionModel
{
public int? Id { get; set; }
public string Name { get; set; }
}

On an .NET MVC controller, what does the mapping?

So I have a action method that takes a fancy Cart object:
[HttpPost]
public JsonResult BuildTransaction(Cart cart) { }
The Cart model:
public class Cart
{
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
I throw some JSON at the route, that looks like this:
object cart = new {
UserId = uid,
FirstName = "John",
LastName = "Travlota",
Address = new {
Line1 = "Ramsdean Grange",
Town = "boom town",
PostCode = "dd7 7sx"
}
};
var request = client.PostAsJsonAsync("BuildTransaction", cart);
The result, I have a cart of type Cart to play with in my controller. Fantastic!
My question is, how does .NET do this mapping? I imagine its someplace in the OnActionExecute but what/how does it do this.
If I wanted to mimic this functionality, what would I do? Do I really need an external tool like AutoMapper if MVC seems perfectly capable of doing it without it?
This is done by the Model Binder. (System.Web.Mvc.DefaultModelBinder)
You can implement a custom model binder like so:
Controller:
public ActionResult Create([ModelBinder(typeof(CreateModelBinder))] CreateViewModel vModel)
{
}
Model Binder:
public class CreateModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//assign request parameters here, and return a CreateViewModel
//for example
CreateViewModel cVM = new CreateViewModel();
cVM.Name = controllerContext.HttpContext.Request.Params["Name"];
return cVM;
}
}
More info: http://www.dotnetcurry.com/ShowArticle.aspx?ID=584
https://stackoverflow.com/a/1249602/1324019
First MVC receives a post (for example) which contains your html input values and the name associated with each of them.
Then it checks the properties in the expected object (the model type) and tries to find a name which matches in the form received, and so on.
It all happens in the ModelBinder, you can even change the way it is done since this is an extension point.
So this is for the how, and about using AutoMapper, you don't need it here.
This is Mvc Model Binding. MVC has a set of a default model binders. It uses the DefaultModelBinder object as default for your post requests, but it also have the 3 following objects registered by default.
HttpPostedFiledModelBinder
ByteArrayModelBinder
LinqBinaryModelBinder
You can also create your own binders and associate them to a parameter with an attribute on a parameter as #Mansfield pointed out. But you can also register them globally for a specific type as follow (In Application_Start for example)
//Register FooModelBinder for all posted objects that are of type Foo
ModelBinders.Binders.Add(typeof(Foo),new FooModelBinder());
And if for some reason you want to reinvent the wheel you can also change de DefaultModelBinder
ModelBinders.Binders.DefaultBinder = new CustomDefaultModelBinder();
Here's a very simple implemention of a ModelBinder for Foo type
public class FooModelBinder: IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) {
IUnvalidatedValueProvider provider = (IUnvalidatedValueProvider)bindingContext.ValueProvider;
return new Foo {
Bar = provider.GetValue("Bar", true).AttemptedValue,
Banana= provider.GetValue("Banana", true).AttemptedValue
};
}
#endregion
}
The ASP.NET MVC model binder is what does this translation of request parameter to class instances. This great piece of functionality operates based on conventions, so as long as you follow default conventions (which means that your request parameters need to have the same name as the names of the properties of your class). So yes, in most cases the default model binder behavior is fine and you don't need a library like AutoMapper.
If you want to know more about when model binding occurs, this article goes into the MVC pipeline in great detail. If you just want to know more about model binding, I found this two page tutorial a great help: part 1 and part 2.

asp.NET MVC 2 DataAnnotations UpdateModel<T> validation

I'm trying to use DataAnnotations to add validation to my models in asp.NET MVC 2 RC2, using TryUpdateModel
var user = UserManager.Find(id);
this.TryUpdateModel<IProvisioningObject>(user, form.ToValueProvider());
This updates the model, but the validation is never called. I tried using TryUpdateModel as well (which is the direct type of user), not using the form value provider, using ProvisioningObject directly (which has the validation metadata), to no avail.
Googling for examples only gives me ways to use DataAnnotations by binding through a parameter
public ActionResult Update(User user)
Which I dislike for update scenarios.
Any tips and/or solutions?
EDIT
My objects are auto-generated objects from a WCF service.
I made partials to be able to add DataAnnotations.
I call TryUpdateModel three times because it apparently doesn't support inheritance, which I think is also my problem with DataAnnotations. I specify the validation attributes for ProvisioningObject, and the binding doesn't look for inherited stuff like that.
[MetadataType(typeof(ProvisioningObjectMetadata))]
public partial class ProvisioningObject : IProvisioningObject
{
public string DisplayNameInvariant { get { return string.IsNullOrEmpty(this.DisplayName) ? this.Name : this.DisplayName; } }
}
[MetadataType(typeof(UserMetadata))]
public partial class User : IUser
{
}
public class ProvisioningObjectMetadata
{
[DisplayName("Country")]
public string CountryIsoCode { get; set; }
[Required(ErrorMessageResourceType = typeof(Properties.Validation), ErrorMessageResourceName = "DisplayNameIsRequired")]
[TempValidator]
public string DisplayName { get; set; }
}
public class UserMetadata
{
[DisplayName("Username")]
public string Name { get; set; }
}
// Controller action
public ActionResult Update(string id, FormCollection form)
{
var user = UserManager.Find(id);
this.TryUpdateModel<IUser>(user.User, form.ToValueProvider());
this.TryUpdateModel<IPerson>(user.User, form.ToValueProvider());
this.TryUpdateModel<IProvisioningObject>(user.User, form.ToValueProvider());
if (ModelState.IsValid) // always true
{
return Redirect;
}
else
{
return View();
}
}
If I add the metadata for DisplayName in UserMetadata, it works as expected, but that seems very redundant for nothing. And it would mean I would also have to copy/paste all my inherited interfaces so TryUpdateModel behaves appropriately.
I guess I'm looking for a way that doesn't require me to copy and paste my validation attributes to inherited classes.
New Answer:
"My objects are auto-generated objects from a WCF service."
Autogenerated objects won't have any attributes on them. Are you defining your objects and their attributes on the server side or on the client side?
Old Answer:
If your metadata is not on IProvisioningObject then no validation will be called. The MVC2 default model binder only knows how to find "extra" [MetadataType(buddyClass)] validation information.
For update scenarios bind against DTOs and then map the DTOs, if IsValid() to your main model classes.
Implement IDataErrorInfo interface in your partial class
You will have to write custom validation for each field(where you can use data annotation class to validate each required property)
If you need code example then let me know. I will write it for you!
source: http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/mvc/tutorial-37-cs.aspx
How do you know that the validation is not being called? Are you checking ModelState.IsValid in your update controller and finding that it is erroneously coming back true?
A typical update pattern is:
UpdateModel(model);
if(!ModelState.IsValid) return View(model);
return RedirectToAction("Index");
If you are expecting some "IsValid" on your model to automatically be called, that will not happen. The data annotations work behind the scenes with the ModelState dictionary on the Controller base class.

Categories

Resources