ASP.NET Core MVC Interview Questions
ASP.NET Core MVC is a rich framework for building web apps and APIs using the Model-View-Controller (MVC) design pattern. It provides a patterns-based way to build dynamic websites that enables a clean separation of concerns. It gives you full control over markup, supports TDD-friendly development and uses the latest web standards. Following are some selected Interview Questions regarding ASP.NET Core MVC technologies and development.
What is ASP.NET Core?
ASP.NET Core is the Open-Source version of Microsoft ASP.NET. You can develop and run your ASP.NET Core apps cross-platform on Windows, Mac and Linux. It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions. Also, multiple versions of ASP.NET Core can exist side by side on the same server. Meaning one app can adopt the latest version, while other apps keep running on the version they were tested on.
What are some benefits of ASP.NET Core over the classic ASP.NET?
Asp.net Core is a new version of Asp.net released by Microsoft. Although both project templates use Full .Net Framework. ASP.NET Web Application is for creating projects using legacy version of ASP.NET MVC in which you can use Global.asax. ASP.NET Core Web Application is totally new concept in which wwwroot folder, using task runners and everything is through OWIN middleware.Main differences:
- Asp.Net Build for Windows only while Asp.Net Core Build for Windows, Mac and Linux.
- Asp.Net Supports WebForm, Asp.Net MVC and Asp.Net WebAPI, whereas Asp.Net Core does not support WebForm. It supports MVC, Web API and Asp.Net Web pages originally added in .Net Core 2.0.
- Asp.Net support C#, VB and many other languages and also support WCF, WPF and WF while Asp.Net Core support only C#, F# language.
- You need to re-compile after the code change in Asp.Net while in ASP.NET Core browser will compile and executed the code and no need for re-compile.
How to explain OWIN and Katana in simple words?
OWIN (Open Web Interface for .NET) is a standard ( OWIN Specification) and Katana is a .NET library. OWIN defines a standard interface between .NET web servers and web applications. The goal of OWIN is to decouple web applications from the web server by introducing an abstraction layer. Such an abstraction enables you to run the same application on all the web servers that support OWIN. Katana is a set of components by Microsoft built using OWIN specifications . Some of these components include Web API, ASP.NET Identity and SignalR.
Can ASP.NET Core work with the .NET framework?
Yes. ASP.NET Core works with .NET framework and this is officially supported by Microsoft. One important benefit of using Full .NET framework with Asp.Net core is the availability of mature libraries and frameworks that are developed mainly to target previous version of .NET.
Why this error: A potentially dangerous Request.Form value was detected from the client
This error is because you have HTML tags in your POST request . It can be an indication of a cross site scripting attack, which is why Asp.net does not allow it by default. So, you should encode at the point where some specific characters may become dangerous because they cross into a different sub-language where they have special meaning.
The solution for this error is that you should either HTML encode before submitting , or disable the warning and potentially expose yourself to XSS.
Which protocol is used to call web service?
SOAP (Simple Object Access Protocol) is the preferred protocol used for exchanging web service data. Simple Object Access Protocol uses the XML information set for the message format and relies on the application layer protocols such as the HTTP or SMTP for negotiating and transmitting the messages.
Explain the Cross page posting and Redirect Permanent in ASP.Net?
Cross-page posting means that you are posting form data to another page as opposed to posting form data back to the same page (as is the default in ASP.NET). This can be useful when you want to post data to another page and don't want to incur the overhead of reloading the current page simply to redirect the user to another page via an HTTP 302 (i.e. Response.Redirect).
Redirect Permanent is a permanent redirection from the requested URL to a given URL happens. Once it is done, it returns 301 moved responses permanently.
Explain how HTTP protocol works?
- First, the Browser looks up the destination server. If requested object is in DNS cache, it uses that information. Otherwise, DNS querying is performed until the destination server's IP address is found.
- Then, your browser opens a TCP connection to the destination server and sends the request according to Hypertext Transfer Protocol (HTTP). This step is much more complex with HTTPS.
- The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the browser. Browser receives HTTP response and may close the TCP connection, or reuse it for another request.
What is MVC?
MVC (Model–View–Controller) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements, the model (data), the view (user-interface), and the controller (application logic). Each of these components are built to handle specific development aspects of an application.
Using the Model–View–Controller pattern for websites, requests are routed to a Controller (application logic) that is responsible for working with the Model (data) to perform actions and/or retrieve data. The Controller (application logic) chooses the View (user-interface) to display and provides it with the Model (data). The View (user-interface) renders the final page, based on the data in the Model.
What is the difference between ASP.NET Webforms and ASP.NET MVC?
ASP.NET Web Forms and MVC are two web frameworks developed by Microsoft. Each of these web frameworks offers advantages/disadvantages - some of which need to be considered when developing a web application.
- Asp.Net Web Form follow a traditional event-driven development model whereas Asp.Net MVC is a lightweight and follows MVC (Model, View, Controller) pattern based development, model.
- Asp.Net Web Form supports view state for state management at the client side while Asp.Net MVC does not support view state.
- Asp.Net Web Form follows Web Forms Syntax while Asp.Net MVC follow customizable syntax (Razor as default).
- Asp.Net Web Form has User Controls for code re-usability whereas Asp.Net MVC has Partial Views for code re-usability.
- In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic while in Asp.Net MVC, Views and logic are kept separately.
- Finally, Asp.Net Web Form is not Open Source while Asp.Net Web MVC is an Open Source.
How to enable Cross-Origin Requests (CORS) in ASP.NET Core?
You have to configure a CORS policy at application startup in the ConfigureServices method.
The CorsPolicyBuilder in builder allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:
What is dependency injection?
Dependency Injection is the ability of an object to supply dependencies of another object. When a software component depends upon other resources to complete its intended purpose, it needs to know which resources it needs to communicate with, where to locate them and how to communicate with them.
Dependency Injection allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Typically, the receiving object is called a client and the passed-in object is called a service. The code that passes the service to the client is called the injector . Instead of the client specifying which service it will use, the injector tells the client what service to use. The 'injection' refers to the passing of a dependency (a service) into the client that uses it.
Dependency injection makes testing easier. The injection can be done through constructor.
What is In-memory cache ?
With ASP.NET Core , it is now possible to cache the data within the application. In-memory cache is the simplest way of caching by ASP.NET Core that stores the data in memory on web server. This is known as In-Memory Caching in ASP.NET Core. It is a service that you can incorporate into your application using dependency injection. IMemoryCache interface instance in the constructor enables the In-memory caching service via ASP.NET Core dependency Injection .
Apps running on multiple server should ensure that sessions are sticky if they are using in-memory cache. Sticky Sessions responsible to redirect subsequent client requests to same server.
How to enable the in-memory cache in ASP.NET Core project?
You can enable the in-memory cache in the ConfigureServices method in the Startup class as shown in the code snippet below.
How to prevent Cross-Site Scripting (XSS) in ASP.NET Core?
What's the difference between OpenID and OAuth?
OpenID is used for authentication while OAuth is used for authorization.
- OpenID is an open standard and decentralized authentication protocol controlled by the OpenID Foundation and deals with authentication (ie. proving who you are). It take the form of a unique URI managed by some "OpenID provider" i.e identity provider (idP).
- OAuth is an open standard for access delegation deals with authorisation (ie. to grant access to functionality/data/etc.. without having to deal with the original authentication). It can be used in conjunction with XACML where OAuth is used for ownership consent and access delegation whereas XACML is used to define the authorization policies.
Explain the Middleware in ASP.NET Core.
Middleware is a software that's assembled into an app pipeline to handle requests and responses in ASP.NET Core application. Middlewares build the request pipeline. These middleware components are configured as part of the application startup class in the configure method. Configure methods set up a request processing pipeline for an ASP.NET Core application. It consists of a sequence of request delegates called one after the other.
You can configure the request delegates through the 'Run' , 'Map' , and 'Use' method on IApplicationBuilder. You can set the order of middleware execution in the request pipeline. Each middleware adds or modifies http request and optionally passes control to the next middleware component.
What is the Area?
Area allows you to partition the large application into smaller units where each unit contains a separate MVC folder structure . In general, for a large application; Models, Views and controllers are kept physically in different folders, and asp.net MVC uses naming conventions to create the relationship between these components.
A single MVC application may have any number of areas. Each area has its own controllers, models, views. Physically, areas are put under separate folders. Moreover, using areas, multiple developers can work on the same web application project.
What is the purpose of a question mark(?) after a type (int?)
It is a shorthand for Nullable
How to get parameter in url ( by C# for .net)
You can use static ParseQueryString() method of System.Web.HttpUtility class that returns NameValueCollection.
ParseQueryString() method parses a query string into a NameValueCollection using UTF8 encoding . URL-encoded characters are decoded and multiple occurrences of the same query string parameter are listed as a single entry with a comma separating each value.
Why this error: 'Sys' is undefined
This error is because there was probably a script in your page that was using the "Sys" function, it is not defined yet. When working on an asp.net web application, you have to enable CDN so that Microsoft can download the "Sys" library. Setting EnableCdn="true" would ensure that the Sys library is downloaded before it is used.
ScriptManager.EnableCdn Property determines whether the current page loads client script references from CDN ( Content Delivery Network ) paths.
What are these special tags?<% %>, <%$ %>, <%@ %>, <%= %>, <%# %>, <%: %>, <%#: %>, <%-- --%>
- <% %> - Inline code (especially logic flow).
- <%# %> - Data binding expressions.
- <%$ %> - Evaluating expressions (like resource variables).
- <%@ %> - Page directives, registering assemblies, importing namespaces, etc.
- <%= %> - Short-hand for Response.Write (discussed here).
- <%: %> - Short-hand for Response.Write(Server.HTMLEncode()) ASP.net 4.0+.
- <%#: %> - Data binding expressions and is automatically HTMLEncoded.
- <%-- --%> - Server-side comments.
How to assign null value to DateTime object?
DateTime is a non-nullable value type. For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue , because it is a value type rather than a reference type.
You can set a nullable DateTime, like the following:
Or use the longer form:
And you can check the value with:
What is an IIS application pool?
IIS is an extensible web server software used to host one or more web application. Every web application or a part of the website, you can run under an application pool . You can control some basic settings of the website using an application pool. So you can have any number of application pool depending upon on servers capacity.
Application pools allow you to isolate your applications from one another, even if they are running on the same server. This way, if there is an error in one app, it won't take down other applications. Additionally, Applications Pools allow you to separate different apps which require different levels of security.
How can you set the Content-Type header in a HttpClient request?
MediaTypeHeaderValue represents a media type used in a Content-Type header as defined in the RFC 2616.
MediaTypeHeaderValue is a label for the type of content the requests contains. Another name for the values would be MIME types . (Multipurpose Internet Mail Extensions)
What is ViewModel in MVC?
A view model in MVC is an object that contains all the properties and methods necessary to render a view. It is used to pass data from controller to strongly-typed view. This means that it provide a convenient object to pass to a rendering engine to create an HTML page. It would be rendered useless without the View, so it typically isn't reusable across multiple Views and Controllers like a standard Model is.
One of many reasons to use a view model is that the view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc.Characteristics of View Models:
- It documents a view by consisting only fields, that are represented in view.
- It may contain specific validation rules using data annotations or IDataErrorInfo.
- It defines how a view should look (for LabelFor, EditorFor, DisplayFor helpers).
- It can combine values from different database entities.
How to Increase Message Size Quota?
You'll want to increase the message size quotas, in the App.config or Web.config file:
MaxBufferSize is of type int. So the max value it can support is Int32.MaxValue (2147483647) to avail the maximum allowable size.
MaxReceivedMessageSize on the other hand is of type long or Int64 and the max value it supports is: 9,223,372,036,854,775,807.
How to increase the time out for request/response ?
You can set "executionTimeout" value in web.config under
The executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET . It is important to note that this time-out applies only if the debug attribute in the compilation element is False.
What is AutoEventWireup?
When a Page is requested, it raises various events which are considered to be part of it's lifecycle. AutoEventWireup is an attribute of the @ Page directive.
The AutoEventWireup attribute may have a value of true or false. The AutoEventWireUp property when True, automatically wires up some of these built-in events in the Page life cycle to their handlers. The value of AutoEventWireup is false means that your Page_Load event will not be automatically hooked to the page's Load event and so on for PreRender and the other page lifecycle events.
Difference Between ViewResult() and ActionResult()
ActionResult is an abstract class that can have several subtypes. ViewResult is a subclass of ActionResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult , your controller isn't promising to return a view. You could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
When you set Action's return type ActionResult , you can return any subtype of ActionResult e.g Json, PartialView, View, RedirectToAction. But when you use subtype as in this case ViewResult you are bounding your action that it will only return subtype as result which in this case is View.
Can you overload controller methods in ASP.NET MVC?
A method used as a controller action cannot be overloaded. This means that you can not do it directly. If you have to overload the action Method in Asp.net MVC indirectly then you can use the attribute. You have to change the ActionName like this code snippet.