What is an Action Filter? What it is used for? How to implement? What action filters you have implemented before?
Action filters are custom attributes that provide a declarative means to add pre-action and post-action behavior to controller action methods.
TYPES:
- Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. TheAuthorizeAttribute class is one example of an authorization filter.
- Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
- Result filter, which wraps execution of theActionResult This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.
- Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. TheHandleErrorAttributeclass is one example of an exception filter.
IMPLEMENT: Decorate Above Class or Method
CUSTOM ACTION FILTERS: inherits from ActionFilterAttribute. ActionFilterAttribute is an abstract class that has four virtual methods that you can override: OnActionExecuting, OnActionExecuted, OnResultExecuting, and OnResultExecuted. To implement an action filter, you must override at least one of these methods.
public class LoggingFilterAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)
What is a global Action Filter? What it is used for? How to implement?
A filter that applies to a complete project/web application.
Registering global action filter
Now, without touching any controller let’s put our evil Buuu! in place. Open global. asax and modify Application_Start event so it looks like follows.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register global filter
GlobalFilters.Filters.Add(new MyActionFilterAttribute());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Explain significance of routing?
-ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods.
-In ASP.NET Routing mechanism a routing table is maintained which is created when the web application first starts.
-The route table is present in the Global.asax file.
-In routing mechanism the physical path of page will not be used in URL and therefore hiding the application file system hierarchy from outer world.
-By using the routing mechanism the URL search becomes more user friendly.
Explain the main function of URL routing system in ASP.NET MVC?
URL routing system provides flexibility to the system and it also enables to define new URL mapping rules that can be used with web applications.
-URL routing system is used to map the application and its routing information gets passed to right controller and action method.
-URL routing system processes and executes the method to run the application without using many designed rules.
-It is used to construct the outgoing URLs that can be used to handle the actions that have the ability to map both incoming and outgoing URLs that adds more flexibility to the application code.
-It follows the rules to execute the application globally and handle the logic that is required for the application.
What is repository pattern in MVC.NET?
-Repository pattern is useful for decoupling entity operations form presentation, which allows easy mocking and unit testing.
-The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation.
-Most common queries should also be hard coded to the Repositories as methods. Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameterless for framework to call, and the second one which takes repository as an input:
class myController: Controller
{
private IMyRepository repository;
// overloaded constructor
public myController(IMyRepository repository)
{
this.repository = repository;
}
// default constructor for framework to call
public myController()
{
//concreate implementation
myController(new someRepository());
}
public ActionResult Load()
{
// loading data from repository
var myData = repository.Load();
}
}
Can you explain why it is useful to use MVC instead of WebForms?
-MVC allows the user to write less amount of code to build the web applications as lots of components are integrated to provide the flexibility in the program.
-Lot of data control options is being provided that can be used in ViewState.
-The application tasks are separated into components to make it easier for the programmers to write the applications but at the same time the amount of the code also increases.
-Main focus remains on the testability and maintainability of the projects that is being carried out in large projects.
-It is being used for the projects that require rapid application development.
Explain the advantages of ASP.NET MVC framework?
MVC framework is divided in model, view and controller which help to manage complex application. it divides the application in input logic, business logic and UI logic.
-MVC framework does not use view state or server-based forms which eliminate the problem of load time delays of HTML pages.
– MVC support ASP.NET routing which provide better URL mapping. In ASP.NET routing URL can be very useful for Search Engine Optimization (SEO) and Representation State Transfer (REST).
-MVC Framework support better development of test-driven development (TDD) application.
-In MVC Framework Testing becomes very easier. Individual UI test is also possible.
What is the Request flow used for ASP.NET MVC framework?
Request flow handles the request from the clients and passes it to the server. The Request flow is as follows:
-Request is being taken from User to controller.
-Controller processes the request from the user and creates a data Model of that particular request.
-Data model that is being created is then passed to View that handles the frontend or the design.
-View then transforms the Data Model by using its own functions in an appropriate output format.
-The output format that is being given by the View is then gets rendered to the Browser and the View will be seen by the user.
What is custom routing? What is a Routing constraint? Where and How to implement this?
Editing the default routes.MapRoute in global.aspx. Or adding additional Routes.
- Regular Expression Constraints
- HttpMethod Constraints
- CatchAll Values
What is MVC, Advantages and Disadvantages?
Model View Controller. MVC is architectural pattern which separates the representation and the user interaction. It’s divided in three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task. The “View” is responsible for look and feel. “Model” represents the real world object and provides data to the “View”. The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.
There are two big benefits of MVC:- Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent. Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.
What is the requestFlow used for in ASP.Net MVC Framework?
Request flow handles the request from the clients and passes it to the server. The Request flow is as follows:
-Request is being taken from User to controller.
-Controller processes the request from the user and creates a data Model of that particular request.
-Data model that is being created is then passed to View that handles the frontend or the design.
-View then transforms the Data Model by using its own functions in an appropriate output format.
-The output format that is being given by the View is then gets rendered to the Browser and the View will be seen by the user.
What is Razor? Advantages?
Razor is not a new programming language itself, but uses C# syntax for embedding code in a page without the ASP.NET delimiters: <%= %> . It is a simple-syntax view engine and was released as part of ASP.NET MVC3.
Razor syntax proccessed on the server : https://stackoverflow.com/questions/32078645/how-does-microsoft-razor-syntax-run-server-side-code-without-exposing-it-to-the
MVC Razor requires less code writing.
Explain different Return Types from Controller Action methods?
There are total nine return types we can use to return results from controller to view.
-The base type of all these result types is ActionResult.
1. ViewResult (View) : This return type is used to return a webpage from an action method.
2. PartialviewResult (Partialview) : This return type is used to send a part of a view which will be rendered in another view.
3. RedirectResult (Redirect) : This return type is used to redirect to any other controller and action method depending on the URL.
4. RedirectToRouteResult (RedirectToAction, RedirectToRoute) : This return type is used when we want to redirect to any other action method.
5. ContentResult (Content) : This return type is used to return HTTP content type like text/plain as the result of the action
6. jsonResult (json) : This return type is used when we want to return a JSON message.
7. javascriptResult (javascript) : This return type is used to return JavaScript code that will run in browser.
8. FileResult (File) : This return type is used to send binary output in response.
9. EmptyResult : This return type is used to return nothing (void) in the result.
What is a ViewData? When and how is this used?
Sending data from controller to view, has to be typecasted or un-boxed
What is a ViewBag? When and how is this used?
-Helps to maintain data when you move from controller to view. Or view to controller
-Used to pass data from controller to corresponding view.
-Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between Tempdata, ViewData and ViewBag?
TempData is used to share data between controller actions. If your controller does a RedirectToAction and the target action needs data (perhaps a particular model instance) to act upon, you can store this data in TempData. Using TempData is similar to storing it in the session, but only for one round-trip. You use TempData when you need to pass data to another controller action rather than a view for rendering.
-ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
-ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
-ViewData requires typecasting for complex data type and check for null values to avoid error.
-ViewBag doesn’t require typecasting for complex data type.
Viewdata vs Viewbag vs Tempdata
What is partial View? Which are the different ways to implement this?
Partial view is like a regular view with a file extension .cshtml. We can use partial views in a situation where we need a header, footer reused for an MVC web application.
Html.RenderPartial(“~/Views/Shared/_Product.cshtml”, product);
@Html.Partial(“~/Views/Shared/_Product.cshtml”, product);
Explain Routing in MVC?
Below are the steps how control flows in MVC (Model, view and controller) architecture:-
- All end user requests are first sent to the controller.
- The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
- The final view is then attached with the model data and sent as a response to the end user on the browser.
How to Implement Windows Authentication and Forms Authentication in MVC?
Enable in web configuration file. Decorate the class or method
How do you do validations in MVC?
- using System.ComponentModel.DataAnnotations;
then decorate above each field required for validation. Or class.
How to implement a custom error page?
in web.config or a config file. Add or edit <customErrors mode=”RemoteOnly” defaultRedirect=”~/ErrorPages/Oops.aspx”>
<error statusCode=”404″ redirect=”~/ErrorPages/404.aspx” />
</customErrors>
How do you implement Ajax in MVC?
Add the ASP.NET AJAX library files. Then an Ajax.ActionLink method, call and use Ajax methods
How to send result back in JSON format in MVC?
In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a simple sample code which returns back “Customer” object in JSON format using “JsonResult”.
public JsonResult getCustomer()
{
Customer obj = new Customer();
obj.CustomerCode = “1001”;
obj.CustomerName = “Shiv”;
return Json(obj,JsonRequestBehavior.AllowGet);
}
Below is the JSON output of the above code if you invoke the action via the browser.
What is the latest version of MVC?
When this note was written, four versions where released of MVC. MVC 1 , MVC 2, MVC 3 and MVC 4. So the latest is MVC 4.
What is the difference between each version of MVC?
MVC2-> Client-Side Validation Templated Helpers Areas Asynchronous Controllers Html.ValidationSummary Helper Method DefaultValueAttribute in Action-Method Parameters Binding Binary Data with Model Binders DataAnnotations Attributes Model-Validator Providers New RequireHttpsAttribute Action Filter Templated Helpers Display Model-Level Errors
MVC3->
- Razor
- Readymade project templates
- HTML 5 enabled templatesSupport for Multiple View EnginesJavaScript and Ajax
- Model Validation Improvements
MVC4->
- NET Web API
- Refreshed and modernized default project templatesNew mobile project template
- Many new features to support mobile apps
- Enhanced support for asynchronous methods
Describe how you use polymorphism in tools which realize dependency injection in MVC?
Why JSon not xml?
JSON is processed more easily because its structure is simpler. JSON is easier to read for both humans and machines. JSON is more easily mapped to Object Oriented Systems.
What are the settings to be done for the Routing to work properly in an MVC application ?
The settings must be done in 2 places for the routing to work properly.They are:
- i) Web.Config File : In the web.config file, the ASP.NET routing has to be enabled.
- ii) Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.
- Is the route {controller}{action}/{id} a valid route definition or not and why ?
{controller}{action}/{id} is not a valid route definition.
The reason is that, it has no literal value or delimiter between the placeholders.
If there is no literal, the routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.
Explain about default route, {resource}.axd/{*pathInfo} …
With the help of this default route {resource}.axd/{*pathInfo}, you can prevent requests for the web resources files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
Explain the difference between adding routes, to a web application and to an mvc application ?
We use MapPageRoute() method of a RouteCollection class for adding routes to a webforms application, whereas MapRoute() method is used to add routes to an MVC application.
Is there any way to handle variable number of segments in a route definition ?
You can handle variable number of segments in a route definition by using a route with a catch-all parameter.
Example:
controller/{action}/{*parametervalues}
Here * reffers to catch-all parameter.
Explain with examples for scenarios when routing is not applied?
Below are the 2 scenarios where routing is not applied.
http://www.dotnetfunda.com/interview/showcatquestion.aspx?start=15&page=2&category=176
- i) A Physical File is found that Matches the URL Pattern – This default behavior can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
- ii) Routing Is Explicitly Disabled for a URL Pattern – By using the RouteCollection.Ignore() method, you can prevent routing from handling certain requests.
- Explain the usage of action filters in an MVC application ?
Action filter in an mvc application is used to perform some additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
Action filter is an attribute that implements the abstract FilterAttribute class.
In an MVC application, which filter executes first and which is the last ?
As there are different types of filters in an MVC application, the Authorization filter is the one which executes first and Exception filters executes in the end.
How do you add constraints to a route ?
There are 2 ways for adding constraints to a route. They are:
- i) By using Regular Expressions and
- ii) By using an object which implements IRouteConstraint interface.
- Advantage of routing
Without using Routing in an ASP.NET MVC application, the incoming browser request should be mapped to a physical file. The thing is that if the file is not there, then you will get a page not found error.
By using Routing, it will make use of URLs where there is no need of mapping to specific files in a web site.
This is because, for the URL, there is no need to map to a file, you can use URLs that are descriptive of the user’s action and therefore are more easily understood by users.