Difference between ASP.NET MVC 3 and 4? [closed] - asp.net-mvc

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is there a comprehensive list that explains all of the new features of MVC4 and what all has changed from MVC3?
(The release notes are not much helpful)

Copied and pasted from MVC4 Release Notes:
•Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a new, strongly typed HTTP object model. The same programming model and HTTP pipeline is symmetrically available on the client through the new HttpClient type.
•Full support for routes: ASP.NET Web API supports the full set of route capabilities of ASP.NET Routing, including route parameters and constraints. Additionally, use simple conventions to map actions to HTTP methods.
•Content negotiation: The client and server can work together to determine the right format for data being returned from a web API. ASP.NET Web API provides default support for XML, JSON, and Form URL-encoded formats and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy.
•Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by the Web API actions. Validation is also performed on action parameters based on data annotations.
•Filters: ASP.NET Web API supports filters including well-known filters such as the [Authorize] attribute. You can author and plug in your own filters for actions, authorization and exception handling.
•Query composition: Use the [Queryable] filter attribute on an action that returns IQueryable to enable support for querying your web API via the OData query conventions.
•Improved testability: Rather than setting HTTP details in static context objects, web API actions work with instances of HttpRequestMessage and HttpResponseMessage. Create a unit test project along with your Web API project to get started quickly writing unit tests for your Web API functionality.
•Code-based configuration: ASP.NET Web API configuration is accomplished solely through code, leaving your config files clean. Use the provide service locator pattern to configure extensibility points.
•Improved support for Inversion of Control (IoC) containers: ASP.NET Web API provides great support for IoC containers through an improved dependency resolver abstraction
•Self-host: Web APIs can be hosted in your own process in addition to IIS while still using the full power of routes and other features of Web API.
•Create custom help and test pages: You now can easily build custom help and test pages for your web APIs by using the new IApiExplorer service to get a complete runtime description of your web APIs.
•Monitoring and diagnostics: ASP.NET Web API now provides light weight tracing infrastructure that makes it easy to integrate with existing logging solutions such as System.Diagnostics, ETW and third party logging frameworks. You can enable tracing by providing an ITraceWriter implementation and adding it to your web API configuration.
•Link generation: Use the ASP.NET Web API UrlHelper to generate links to related resources in the same application.
•Web API project template: Select the new Web API project form the New MVC 4 Project wizard to quickly get up and running with ASP.NET Web API.
•Scaffolding: Use the Add Controller dialog to quickly scaffold a web API controller based on an Entity Framework based model type.

Copy and paste from Whats new in MVC4 - MVC3 Vs MVC4
Whats new in MVC4 - MVC3 Vs MVC4
Enhancements to Default Project Templates
The template that is used to create new ASP.NET MVC 4 projects has been updated to create a more modern-looking website
Mobile Project Template
If you’re starting a new project and want to create a site specifically for mobile and tablet browsers, you can use the new Mobile Application project template. This is based on jQuery Mobile, an open-source library for building touch-optimized UI
Display Modes
The new Display Modes feature lets an application select views depending on the browser that's making the request. For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")
{
ContextCondition = (context => context.Request.UserAgent.IndexOf
("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
jQuery Mobile, the View Switcher, and Browser Overriding
jQuery Mobile is an open source library for building touch-optimized web UI. If you want to use jQuery Mobile with an ASP.NET MVC 4 application, you can download and install a NuGet package that helps you get started. To install it from the Visual Studio Package Manager Console, type the following command:
Install-Package jQuery.Mobile.MVC
This installs jQuery Mobile and some helper files, including the following:
Views/Shared/Layout.Mobile.cshtml, which is a jQuery Mobile-based layout.
A view-switcher component, which consists of the Views/Shared/ViewSwitcher.cshtml partial view and the ViewSwitcherController.cs controller.
After you install the package, run your application using a mobile browser (or equivalent, like the Firefox User Agent Switcher add-on). You'll see that your pages look quite different, because jQuery Mobile handles layout and styling. To take advantage of this, you can do the following
If visitors click the link, they’re switched to the desktop version of the same page.
Because your desktop layout will not include a view switcher by default, visitors won't have a way to get to mobile mode. To enable this, add the following reference to
_ViewSwitcher to your desktop layout, just inside the element:
#Html.Partial("_ViewSwitcher")
...
Browser Overriding is a core feature of ASP.NET MVC 4 and is available even if you don't install the jQuery.Mobile.MVC package. However, it affects only view, layout, and partial-view selection — it does not affect any other ASP.NET feature that depends on the Request.Browser object.
Recipes for Code Generation in Visual Studio
The new Recipes feature enables Visual Studio to generate solution-specific code based on packages that you can install using NuGet. The Recipes framework makes it easy for developers to write code-generation plugins, which you can also use to replace the built-in code generators for Add Area, Add Controller, and Add View. Because recipes are deployed as NuGet packages, they can easily be checked into source control and shared with all developers on the project automatically. They are also available on a per-solution basis.
Task Support for Asynchronous Controllers
You can now write asynchronous action methods as single methods that return an object of type Task or Task.
For example, if you're using Visual C# 5 (or using the Async CTP), you can create an asynchronous action method that looks like the following:
public async Task Index(string city) {
var newsService = new NewsService();
var sportsService = new SportsService();
return View("Common", new PortalViewModel {
NewsHeadlines = await newsService.GetHeadlinesAsync(),
SportsScores = await sportsService.GetScoresAsync()
});
}
In the previous action method, the calls to newsService.GetHeadlinesAsync and sportsService.GetScoresAsync are called asynchronously and do not block a thread from the thread pool.
Asynchronous action methods that return Task instances can also support timeouts. To make your action method cancellable, add a parameter of type CancellationToken to the action method signature. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds and that displays a TimedOut view to the client if a timeout occurs.
[AsyncTimeout(2500)]
[HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
public async Task Index(string city, CancellationToken cancellationToken) {
var newsService = new NewsService();
var sportsService = new SportsService();
return View("Common", new PortalViewModel {
NewsHeadlines = await newsService.GetHeadlinesAsync(cancellationToken),
SportsScores = await sportsService.GetScoresAsync(cancellationToken)
});
}
Hope this helps. Thanks

Please go through the URL for all MVC 4 new features

MVC 3
Integrated Scaffolding system extensible via NuGet
HTML 5 enabled project templates
Expressive Views including the new Razor View
Engine
Powerful hooks with Dependency Injection and
Global Action Filters
Rich JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
MVC 4
ASP.NET Web API
Refreshed and modernized default project
templates
New mobile project template
Many new features to support mobile apps
Enhanced support for asynchronous methods
Ref : http://dotnet-developers-cafe.blogspot.in/2013/09/difference-between-aspnet-mvc-3-and-mvc.html

Please check the below links to find out the differences.
http://forums.asp.net/t/1753017.aspx
http://www.askamoeba.com/Answer/130/Whats-new-in-MVC4-MVC3-Vs-MVC4
http://forums.asp.net/t/1918539.aspx?Main+difference+between+regular+webapplication+mvc3+and+mvc4+

One of the important feature introduced in MVC 4.0 was of Asynchronous controllers which enables to write the asynchronous action methods. Asynchronous controller allows an operation to get performed without making the working thread idle.
When an asynchronous action is invoked, the following steps occur:
The Web server gets a thread from the thread pool (the worker thread) and schedules it to handle an incoming request. This worker thread initiates an asynchronous operation.
The worker thread is returned to the thread pool to service another Web request.
When the asynchronous operation is complete, it notifies ASP.NET.
The Web server gets a worker thread from the thread pool (which might be a different thread from the thread that started the asynchronous operation) to process the remainder of the request, including rendering the response.
Converting Synchronous Action Methods to Asynchronous Action Methods
Following is the example of synchronous action method and the its asynchronous equivalent version.
Synchronous Controller:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
}
Asynchronous variant of above operation:
public class TestController : AsyncController
{
public void IndexAsync()
{
return View();
}
public ActionResult IndexCompleted()
{
return View();
}
}
Steps:
Synchronous Controllers are the classes derived from the Controller
class to implement an AsyncController instead of deriving the
controller from Controller, derive it from AsyncController class.
Controllers that derive from AsyncController enable ASP.NET to
process asynchronous requests, and they can still service synchronous
action methods.
Corresponding to the synchronous action method in Synchronous
controller you need to create two methods for the action in
asynchronous controller.First method that initiates the asynchronous
process must have a name that consists of the action and the suffix
"Async". The other method that is invoked when the asynchronous
process finishes (the callback method) must have a name that consists
of the action and the suffix "Completed".
In the above sample example, the Index action has been turned into
two methods in asynchronous controller: IndexAsync and
IndexCompleted.
The IndexAsync method returns void while the IndexCompleted method
returns an ActionResult instance. Although the action consists of two
methods, it is accessed using the same URL as for a synchronous
action method (for example, Controller/Index).
Note the following about asynchronous action methods:
If the action name is Sample, the framework will look for SampleAsync and SampleCompleted methods.
View pages should be named Sample.aspx rather than SampleAsync.aspx or SampleCompleted.aspx. (The action name is Sample, not SampleAsync)
A controller cannot contain an asynchronous method named SampleAsync and a synchronous method named Sample. If it does, an AmbiguousMatchException exception is thrown because the SampleAsync action method and the Sample action method have the same request signature.
For more details click here : http://www.counsellingbyabhi.com/2014/05/asynchronous-controllers-in-aspnet-mvc.html

Related

Unity container in ASP.NET MVC

I have a simple question. I'm newer with UnityContainer of Miscrosoft. I'm writing an ASP.NET MVC application with Unity for DI.
Have I a different CONTAINER for each user connected to my web app? Or the CONTAINER is the same for all users?
So if I resolve the life time of an object with ContainerControlledLifetimeManager does it mean that only for one user session this object is always the same?
I hope you understand.
Thanks,
Christian
Lifetime refers to the life of the object created by the DI process. Per request means each request gets its own object. If the object depends on the current user, querystring values on that request or values/presence of Request headers a PerRequest lifetime is appropriate. If you have settings that vary based on location of your service, for example, you saved values from web.config, then a the container is most likely created in global.asa and these objects can live as long as the container lives.
A concrete example:
You have a service as part of your site and you are migrating to vNext of that service. Users can opt-in by clicking a link that includes a parameter like &myService=vNext to see the new behavior. your Factory method uses the value of this parameter to select vNow or vNext for each request.
Here's some pseudo code to get you started:
container.RegisterInstance<IProductFactory>("enterprise", new EnterpriseProductFactory());
container.RegisterInstance<IProductFactory>("retail", new RetailProductFactory());
container.RegisterVersionedServiceFactory<IProductFactorySettings, IProductFactory>();
In this example RegisterVersionedServiceFactory is an extension method that does nothing but decide which of the IProductFactory instances to use for the current request. The factory provides the current instance (there are only two for the life of the service) to use for this request (thousands per seconds).
This pattern is what makes a very large site you probably used recently both very stable and very flexible. New versions of services are rolled out using this exact same pattern to help keep the site very stable.

MessageHandlers vs Filters in asp.net mvc web api project

What's the difference between using a MessageHandler vs a Filter to check for an API key in the request header for an MVC web api project.
I see that there is a well outlined example of a MessageHandler for just that purpose in http://www.asp.net/web-api/overview/working-with-http/http-message-handlers
e.g.
GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiKeyHandler());
But it looks like I can do the same thing using a filter as well.
GlobalConfiguration.Configuration.Filters.Add(new ApiKeyFilter());
Assuming ApiKeyFilter and ApiKeyHandler both just look at the request header and check for an api key, Which way is more efficient? What's the difference?
MessageHandlers run much earlier than filters.
the order is:
-MessageHandler
-Authorization filter
-Model binding
-Other filters
Security related stuff should run as early as possible.

Is there any advantage on using async method of httpclient

I'm working on an MVC 4 application. I've a controller where I make calls to some REST service using the HttpClient class. The controller is a normal controller and the actions are not described with async keyword. Do I get any gain of using PostAsync method of HttpClient class in this case? It's not a fire and forget call and I need the result returned from the service. The ASP.NET thread is going to be blocked anyway till it get the result and so is there advantage?
You don't have any advantage in that case. You have to be either all the way async or all the way synchronous.
The single exception I can think of is when you have a singe synchronous MVC action starting off dozens of async, concurrent requests. In that case you burn one thread to coordinate dozens of others. That would be acceptable.
Side note: Async doesn't apply to most server apps, but in your case it seems like you could benefit from an all-async style solution because you are making a potentially long-running HTTP request. So you might switch to all-async for this one particular MVC action.

Design considerations for heavy loaded asp.net MVC + Web API application and asynchronous message bus

I'm planning to build a quite large application (large in term of concurrent user / number of request, not in term of features).
Basically, I'll have a service somewhere, that is waiting for commands execute them, and acknowledge the completion later. This service will use a service bus to communicate, making the execution eventual, before a acknowledge message is issued.
The consumers of this service can be any kind of application (WPF, SL, ...) but my main (and first) client will be an asp.net MVC application + WebApi (.Net 4.5) or MVC only (.Net 4.0) with ajax controller actions.
The web application will be relying on Ajax call to keep a user friendly responsive application.
I'm quite new to such full blown async architecture, and I'm having some questions to avoid future headache :
my web api calls can take some amount of times. How should I design properly the api to support long running operations (some kind of async?). I've read about the new async keyword, but for the sake of knowledge, I'd like to understand what's behind.
My calls to the service will consist is publishing a message and wait for the ack message. If I wrap this in a single method, how should I write this method? Should I "block" until the ack is received (I suppose I shouldn't)? Should I return a Task object and let the consumer decide?
I'm also wondering if SignalR can help me. With signalR, I think I can use a real "fire and forget" command issuing, and route up to the client to ack message.
Am I completely out of subject, and should I take another approach?
In term of implementation details / framework, I think I'll use :
Rabbitmq as messaging system
Masstransit to abstract the messaging system
asp.MVC 4 to build the UI
Webapi to isolate command issuing out of UI controllers, and to allow other kind of client to issue commands
my web api calls can take some amount of times.
How should I design properly the api to support long
running operations (some kind of async?).
I'm not 100% sure where you're going. You ask questions about Async but also mention message queuing, by throwing in RabbitMQ and MassTransit. Message queuing is asynchronous by default.
You also mention executing commands. If you're referring to CQRS, you seperate commands and queries. But what I'm not 100% about is what you're referring to when mentioning "long running processes".
When you query data, the data should already be present. Preferably in a way that is needed for the question at hand.
When you query data, no long-running-process should be started
When you execute commands, a long-running-processes can be started. But that's why you should use message queuing. Specify a task to start the long running process, create a message for it, throw it onto the queue, forget about it altogether. Some other process in the background will pick it up.
When the command is executed, the long-running-process can be started.
When the command is executed, a database can be updated with data
This data can be used by the API if someone requests data
When using this model, it doesn't matter that the long-running-process might take up to 10 minutes to complete. I won't go into detail on actually having a single thread take up to 10 minutes to complete, including locks on database, but I hope you get the point. Your API will be free almost instantly after throwing a message onto the queue. No need for Async there.
My calls to the service will consist is publishing a message and wait for the ack message.
I don't get this. The .NET Framework and your queuing platform take care of this for you. Why would you wait on an ack?
In MassTransit
Bus.Instance.Publish(new YourMessage{Text = "Hi"});
In NServiceBus
Bus.Publish(new YourMessage{Text = "Hi"});
I'm also wondering if SignalR can help me.
I should think so! Because of the asynchronous nature of messaging, the user has to 'wait' for updates. If you can provide this data by 'pushing' updates via SignalR to the user, all the better.
Am I completely out of subject, and should I take another approach?
Perhaps, I'm still not sure where you're going.
Perhaps read up on the following resources.
Resources:
http://www.udidahan.com/2013/04/28/queries-patterns-and-search-food-for-thought/
http://www.udidahan.com/2011/10/02/why-you-should-be-using-cqrs-almost-everywhere%E2%80%A6/
http://www.udidahan.com/2011/04/22/when-to-avoid-cqrs/
http://www.udidahan.com/2012/12/10/service-oriented-api-implementations/
http://bloggingabout.net/blogs/dennis/archive/2012/04/25/what-is-messaging.aspx
http://bloggingabout.net/blogs/dennis/archive/2013/07/30/partitioning-data-through-events.aspx
http://bloggingabout.net/blogs/dennis/archive/2013/01/04/databases-and-coupling.aspx
my web api calls can take some amount of times. How should I design
properly the api to support long running operations (some kind of
async?). I've read about the new async keyword, but for the sake of
knowledge, I'd like to understand what's behind.
Regarding Async, I saw this link being recommended on another question on stackoverflow:
http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx
It says that when a request is made to an ASP .NET application, a thread is assigned to process the request from a limited thread pool.
An asynchronous controller action releases the thread back to the thread pool so that it is ready to accept addtitional requests. Within the action the operation which needs to be executed asynchronously is assigned to a callback controller action.
The asynchronous controller action is named using Async as the suffix and the callback action has a Completed suffix.
public void NewsAsync(string city) {}
public ActionResult NewsCompleted(string[] headlines) {}
Regarding when to use Async:
In general, use asynchronous pipelines when the following conditions
are true:
The operations are network-bound or I/O-bound instead of CPU-bound.
Testing shows that the blocking operations are a bottleneck in site performance and that IIS can service more requests by using
asynchronous action methods for these blocking calls.
Parallelism is more important than simplicity of code.
You want to provide a mechanism that lets users cancel a long-running request.
I think developing your service using ASP .NET MVC with Web API and using Async controllers where needed would be a good approach to developing a highly available web service.
Using a message based service framework like ServiceStack looks good too:
http://www.servicestack.net/
Additional resources:
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
http://www.codethinked.com/net-40-and-systemthreadingtasks
http://dotnet.dzone.com/news/net-zone-evolution
http://www.aaronstannard.com/post/2011/01/06/asynchonrous-controllers-ASPNET-mvc.aspx
http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2287
http://www.dotnetcurry.com/ShowArticle.aspx?ID=948 // also shows setup of performance tests
http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4
http://visualstudiomagazine.com/articles/2013/07/23/async-actions-in-aspnet-mvc-4.aspx
http://hanselminutes.com/327/everything-net-programmers-know-about-asynchronous-programming-is-wrong
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

Authenticated user and multiple requests (IIS7 MVC3)

This is one of those questions that maybe should go so serverfault, but then maybe there is a code-level solution.
Anyway, here is the question. I have a regular MVC3 application which requires user login to access (uses the Authorize tag on most of the actions). I also have a Silverlight object within the application that makes HTTP GET calls to a controller action which returns an image (in fact this is a map tile). This particular controller action has no authorize tag, and is therefore public.
The Silverlight component runs slow or just blocks, because the MVC application can apparently process only ONE request at a time, as confirmed by firebug. This means that the map tiles can be served only one after the other. Moreover, regular (non-map-related) requests are enqueued too, and everything times out after a while.
So to make a test, I setup another website with the same document root, and I instructed the Silverlight component to read tiles from there. Now tiles ARE requested concurrently and it runs smoothly.
So, is there any way to resolve this situation and use one site only?
If you are using Session on the server action that would explain why requests are queued. Because the Session is not thread safe ASP.NET serializes all requests from the same session and executes them sequentially.

Resources