Binding and overriding a Model Type in ASP.NET 5.0 - model-binding

Previous versions of ASP.Net exposed the inheritable class System.Web.Mvc.DefaultModelBinder, which allowed the method CreateModel in order to return the type of model which the incoming request should bind to. It's very handy for having a single method for different base classes.
This doesn't exist in version 5. You can create Binders easily by inheriting from IModelBinder - in BindModelAsync the Model type can't be set. You can set the ModelMetadata.Model (which I believe would be an instantiation of the target type), but it's unclear how to set the Metadata itself which I think is needed.
Essentially I'm trying to ask this question for the newer framework.

The question turns out to be based on a misconception. The WebAPI stack has never had a DefaultModelBinder, that's the MVC stack. There's so much naming overlap that's it's confusing which is which; that's something ASP.Net 5.0 is trying to overcome.
The answer to this question - how to bind to a model different to the one specified in the method parameters - involves using the Json.NET library. A good overview of two different techniques can be found in this answer.
This works perfectly well for ASP.Net 5.0 too.

Related

Does Microsoft DependencyInjection support non-constructor injection?

I am trying to incorporate Microsoft.Extensions.DependencyInjection into an existing ASP.NET 4.6.1 app.
I know that while .NET Core has it built-in, for 4.6.1 you need to create some initial classes as outlined in http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/. (The article seems to be out of date since the sample code does not show implementation of BeginScope() and Dispose() for IDependencyResolver. If anybody has more updated examples that would be appreciated.)
"Services" accessed by controllers where you are creating instances via constructors is fairly simple but my problem is when I need an instance of "something" that is from a property or method of an existing object.
For example, I have a inherited DbContext that needs an instance of System.Security.Principal.IIdentity that comes from the logged in user.
Another example is an instance of ApplicationUser. ApplicationUser inherits IdentityUser and the current user can be found by calling FindById() method of AppUserManager.
While AppUserManager can easily be instantiated using DI, how can I use DI the inject the output of the FindById() method? I cannot seem to find any documentation or sample code about this for Microsoft based framework. Other frameworks like Unity seem to support Property-based injection.
In essence, can DI be used with all existing classes or do you specifically need to code out the classes to support DI from the beginning? (i.e. only expect parameters to be passed in via constructors and make sure those instances themselves are created via constructors).
The very simple and short answer to your question "Does Microsoft DependencyInjection support non-constructor injection?" is, no.
Out-the-box Microsoft DI does not currently support property injection like other frameworks such as Ninject. If you need that feature, I suggest using those frameworks instead (I cant imagine MS has any plans to add property injection any time soon).
Your other option is to consider how you can refactor your code to use constructor injection instead which is the preferred method

MVC Security Violation - Improperly Controlled Modification of Dynamically-Determined Object Attributes

We are developing an MVC 5 Application and while we ran security scan using Veracode we are getting the below flaw saying
"Improperly Controlled Modification of Dynamically-Determined Object Attributes"
And added this link as reference to fix.
Tried implementing Bind Attribute to my Controllers functions with HTTP Post and the issue is fixed.
So in ASP.NET MVC is it mandatory to use Bind Attribute for all the Post to avoid security violation ?
Or can i ignore this flaw or any other alternative way i can address this as hard coding and maintaining Bind Attributes really gets difficult in real time applications.
Please share your views.
it is not mandatory to use the Bind attribute.
The link which you have posted is basically the dirtiest example they could have came up with. They are directly binding an EF model into the controller, which no real world application would do and I hate Miscrosoft where they show you how easily you can go from DB to Web by applying the dirtiest worst practise patterns without explaining that this is not something you would want to do in real life.
In real life you would create a (View)Model which is tailored to your View. This means the class will ONLY have the properties which you want to accept from the request, therefore you wouldn't really need the Bind attribute in most cases.
EF models are low level classes in your data layer and shouldn't be bound to any controllers IMO.
UPDATE:
Actually on the top of the link they have posted this:
Note It's a common practice to implement the repository pattern in
order to create an abstraction layer between your controller and the
data access layer. To keep these tutorials simple and focused on
teaching how to use the Entity Framework itself, they don't use
repositories. For information about how to implement repositories, see
the ASP.NET Data Access Content Map.
However, this is just talking about the repository pattern, which is a good pattern to abstract your data layer, but the DTO which the repository pattern would return is still too low level for binding to a View.
You should create a model which is tailored to your view and in your controller or service layer you can do the infrastructure mapping between the different layers.

How can I provide my own ICustomTypeDescriptor in ASP.NET MVC?

I'm working on a small library for for ASP.NET MVC 3 that should offer better reusability of model metadata and easy mapping from data entities from / to custom viewmodels. For this I need to be able to provide my own implementation of ICustomTypeDescriptor for three different areas of interest in ASP.NET MVC:
Scaffolding
Validation
Modelbinding
It seems like this could be done by setting System.Web.Mvc.ModelMetadataProviders.Current to my own CustomMetaDataProvider, but this is not nearly enough to cover all three points above.
The problem is that there are several classes in System.Web.Mvc which call directly into this System.Web.TypeDescriptorHelper which is not extensible because it looks like this:
internal static class TypeDescriptorHelper {
public static ICustomTypeDescriptor Get(Type type) {
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
}
The only solution I found is very awkward and required subclassing lots of types from System.Web.Mvc to make it work. I even had to re-implement CustomModelBinderDictionary completely only to overwrite one or two lines of code. So it works, but it is a very messy hack and likely to break the next time I update to a new ASP.NET MVC version.
So here's what I like to know : Did I miss any simple way to do this?
Bonus question: If not and you are from the MVC team, could you consider creating an appropriate extensibility point in MVC 4 ;-)?
Edit: In reply to the question why I need to code my own TypeDescriptor: There are several reasons for this:
1. Most important: I need a workaround for the problem described at https://forums.asp.net/t/1614439.aspx/1
2. Also, I need to insert metadata dynamically for various reasons. For example I want to code my own Bind attribute, but BindAttribute is sealed. So instead of deriving from it, I am emitting a matching BindAttribute dynamically from the TypeDescriptor when detecting my own bind attribute implementation.
According to Brad Wilson (an ASP.NET MVC team member) this issue has been put on the bug list for MVC 4. So it seems there is no good solution for the moment, but hopefully this will be solved when MVC 4 comes out.
For anyone interested in my library for reusable validation and scaffolding metadata and model / viewmodel mapping, feel free to subscribe my blog at https://devermind.wordpress.com/. I'm going to release the library there.
I'm not sure what it is that you're trying to do with custom implementations of Validation, ModelBinding and potentially ModelMetadata, that can't be done with the DependencyResolver functionality in MVC?
The new scaffolding support in the recent Tooling Update for MVC 3 may meet your needs for scaffolding; however I would take a look at possibly hooking into the DependencyResolver functionality for the ModelBinding, ModelMetadata and Validation and see if they can achieve what you are looking for. I had a similar situation recently where I needed to implement a lot of these behaviors from scratch to provide a flexible framework, and I was able to do so with just ModelMetadata and Validation providers using IoC. I also ended up inheriting DynamicObject (or ExpandoObject) in a few cases to give even more flexibility. I know this isn't exactly a direct answer but I'm not sure why you would need access to anything lower than these extensability points?
EDIT: If you're looking to reuse ModelMetadata on similar ViewModels to avoid having to redefine the same ModelMetadata over in multiple places, you might want to consider the implications of this. There are many times when you want certain data restrictions on your entities but these restrictions should be on the DataModel and not the ViewModel. The user may have a slightly more restrictive rules. For example, you may stipulate that certain fields are readonly for the user in the ViewModel, but that the entity used as a DataModel does allow you to modify the value (typically from within your code). Similarly you may run into situations where the ModelMetadata used to generate the Create view for the VideModel might be slightly different than the ViewModel used for the Edit view. Reusing them may seem like a great way to stay consistent and reduce code duplication but it may be something you regret later on. I recently ran into the same issue where I wanted to avoid writing a new ViewModel for each view that may cause a postback, I haven't found a perfect solution I like but I think reusing the ModelMetadata will cause more problems that it might solve in my opinion. Writing ViewModels for views that need them will also probably eliminate your need to implement a custom BindAttribute implementation and the Scaffolding issue.
If I'm right in assuming not wanting to create so many ViewModels with their own Metadata is what's causing you to try and find implementations of a custom BindAttribute, custom Scaffolding, custom ModelMetadata, custom Validation and custom ModelBinding... it may be worth looking at how much time it would actually take to just create the ViewModels.
If you find a better approach, feel free to let me know :-)

EF CTP5 which code generation item to choose?

With EF 4.1 on the way and CTP5 being available for few months now I've decided to try out the new functionality. As I see, there are multiple generation items available (DbContext and three different ObjectContext's). I also noticed they are not interchangable - I was first using the POCO ObjectContext in one of my app and today switched to DbContext and my entire repository broke. It was based on LoadProperty() methods, DeleteObject() and AddObject() methods and those are all missing on DbSet class which is used in DbContext generation.
I know there's a great blog series here http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx introducing the new functionality but it never really says when to choose what.
My requirements are:
ASP.NET MVC application, so lazy
loading mostly won't work coz at page
render it will say that context has
already been disposed (that's why I
need easy support for explicit
loading - in EF4 I did it via
Include(), using POCO context I did
it through LoadProperty() and now
in DbContext I believe I will use
the strongly typed Include()).
We probably won't be needing code-first
features (but you never know).
Difference between those two is mostly in API and feature set. DbContext of course have Include for query and Load but you will find it elsewhere. Moreover when using CTP5 assembly you will have strongy typed Include for both ObjectSet and DbSet (available on IQueryable interface as extension method).
Explicit loading (equivalent to LoadProperty) is performed by Load method on DbReferenceEntry<T> or DbCollectionEntry<T> - check Explicit loading related entities. It works even better then LoadProperty because you can define filter for loading.
You are starting with the wrong assumption that you can't use lazy load with MVC.
If you manage the context at a higher level, you'll be able to do that without problems.

How can I extend the Model in ASP.NET MVC and Entity Framework?

In my first ASP.NET MVC applications, the model was a simple O/R mapping between a table and the classes, managed by the Entity Framework.
Now I would like to add some meat to this skeleton, and introduce business methods for the generated classes. What is the recommended approch to this in ASP.NET MVC (with Entity Framework)? My favorite would be solution which also can be used in a service layer, with no ASP.NET MVC references, so that the same domain logic also could be reused in a desktop client.
Technically, I think it should be possible to extend the generated classes in a way which preserves the additional business logic even if the O/R classes need to be refreshed. (This is more a question related to the Entity Framework however.)
Edit: Many thanks for the contributions, and the information about the next version of Entity Framework (4.0). Building two sets of classes, one auto-generated to represent the data in the persistency layer and one for the actual business logic sounds interesting.
Within MVC.Net, the model is the least clearly defined part. In my opinion, it's basically the rest of your application (i.e. anything not related to the View or the Controller). The O/R Mapping part of your application should probably be outside of the "Model" also, as this is more of a data layer. The Model, should really deal in business objects and create views of your data to pass to the View.
There are lots of differing opinions on this, but I think it's best not to think of MVC.Net as traditional MVC Architecture.
If you are using EF v1.0 right now, the Entity Framework is very intrusive into your application, which means that you cannot create POCO very easily. The way you can extend your model is by using the partial class. So when you refresh your model, the partial class you did will still be valid. The Entity Framework team realizes this is a problem , and have improved this in next version (EF V4.0).
NHibernate is much more friendly and allow you easily extend your business logic.
I really think this blog post by Jeremy D. Miller is very good at pointing out the problem.
Abstract your Business Layer out into another project, then pass an instance of it onto your mvc controller using something like structure map. You can then call this Business Layer from your controller to retrieve your business entities (Model) and pass them on to the UI. This will allow you to resuse your Business Layer in your desktop application.
Not only meat but also some clothes and a style could be added to this project to make it seem chic. It depends on the time you have for the project. If you have time, I could suggest you to get a look to TDD and the frameworks that could be used with TDD such as Castle, NUnit, Moq etc.
As you mentioned a service layer is a must for any project but with these kinds of frameworks you could design your architecture more robust.

Resources