Minifycode 2020-05-15 Viewed 1K times ASP.NET MVC

In this article, you will learn what is MVC interview questions

In this article, we have kept the most asked Asp.Net MVC Interview Questions with their answers to it, So that you can crack the interview with ease

Q1. What is new in Asp.net 5 MVC6 Application?

Answer :

Following thing is are new


 
While creating project we see class, and console with vnext on it.
Now asp.net is modular, class library contains core reference
anything new require to use nuget packages to add new references
Asp.net now is separated from web severs
It can target to multi platform like Linux or Mac.
Asp.net5 MVC, web page and web Api available in WEB API project.
Q2. Explain Project structure in Empty Asp.net 5?

Answer :

Following are default settings


 
Every asp.net 5 class needs to have startup class
It has method call configure and parameter as app of type IApplication.
We can make code changes in state of running application, if we run application state without debugging.
There global.josn was introduced in Solution level
In reference there DNX 4.5.1, DNX core 5.0 are added
For static file there is  www root path
Q3. What is DNX 4.5.1 and DNX core 5.0?

Answer :

It is execution context
It says which platform we want to target
DNX 4.5.1 is full version of .net
This has more dll reference under it namely Microsoft.CSharp, mscorblib, System, System.Core.
DNX 5.0 is just core
This  is good if we want target Linux or Mac machine

There would be similarity most file missing from reference would be  Microsoft.CSharp, mscorblib, System, System.Core.

Q4. Explain website template in Asp.net 5?

Answer :

There would tones of references such as facebook , Microsoft  api etc in Startup.cs


 
Startup constructor with parameter env typeof IHostingEnviroment

There method known as Configureservices which have parameter services typeof IServiceCollection, in that service such as Entity framework is configured.

In reference there DNX 4.5.1, DNX core 5.0 are added

For static file there is  www root path

Q5. Explain different type of IActionResult method? 

Answer :

Following are different type of IActionResult

View
Content
File
Javascript
Json
PartialView
Redirect
RedirectToAction
RedirectToRoute
Q6. What is code block in Razor page?

Answer :

Anything inside or between @{}
We can mix html and C#,vb code
@ is also used to inject expression example @view.Title
Q7. Explain ViewBag, ViewData and Tempdata in Mvc?

Answer :

ViewBag & ViewData:

Helps to maintain data when you move from controller to view.
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.
TemData :

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value.
The difference is the life cycle of the object. TempData keeps the information for the time of an HTTP Request. This mean only from one page to another.
This also works with a 302/303 redirection because it’s in the same HTTP Request.
It helps to maintain data when you move from one controller to other controller or from one action to other action.
In other words, when you redirect, “Tempdata” helps to maintain data between those redirects.
It internally uses session variables. Temp data use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view.
It requires typecasting for complex data type and check for null values to avoid error. It is generally used to store only one time messages like error messages, validation messages.
Q8. Explain Layout page?

Answer :

It is placed under shared folder

We put things which are shared across application in shared folder

It start with underscore , typically it means it is support file

Q9. How to resolve ambiguous method name error in mvc?

Answer :

By adding [HttpGet] or [HttpPost] on the top of method name

Q10. What is Strongly typed view?

Answer :

Accessing model directly in cshtml page is known as strongly typed view.

Example
@model Testclass
Model.Name

Q11. What is Html Helper in MVC?

Answer :

Html helper is extension function provided which contains method call to Html tags.
example textbox , checkbox etc

We don’t have write html tag to create page
Example

@html.EditorFor(m=>m)

Q12. What is asp-for?

Answer :

Asp-for is similar like html helper
It creates html attribute
It is included in html tag
Example
<input asp-for=’Title’/>
Q13.How to display error message for single field?

Answer :

By using html.validationMessageFor() function
Filed should be marked for validation in class.
Example
@Html.ValidationMessageFor(m=>m.Title)

Q14. What is Asp-validation-for?

Answer :

It similar to validationMessagefor html helper class
It is line implementation
Example
<span asp-validation-for=”Title”/>
Q15. How to display summary of error messages?

Answer :

There are 2 ways to display error messages as summary
html.validationSummary()
<div asp-validation-summary=’validation.All’/>
They display error in unordered list
Q16. Which Attribute used to create label?

Answer :

Display attribute used to create label

Q17. How to implement anti forgery in Mvc?

Answer :

Html.AntiForgeryToken() is method used to stop cross site script attack
Add attribute [ValidateAntiForgeryToken] on top of method
Q18. Where Url routing configures is done?

Answer  :

It is done in startup.cs
useMvc is Method
routes table in parameters
route is where single url are defined with following parameter
name :- This should unique
template :- this shows how controller and parameter are defined
default :- if controllers are not defined

Q19. What asp tag used for defining controller?

Answer :

Asp-for-controller is tag used for controller.

Q20. How Authorize attribute is in Mvc?

Answer :

It is used I following way
At the top of method
At the top of class
Q21. What if Authorize is defined at class level but team want allow Index method in control to load?

Answer :

AllowAnonymous is attribute used if we wanted allow method which is under class level Authorize control.
Q22. What is Dependency Injection in ASP.Net MVC?

Answer :

It’s a design pattern and is used for developing loosely couple code.
This will reduce the coding in case of changes on project design so this is vastly used
Q23. How to handle Routing in MVC without configuration?

Answer :

By using Routing attribute we can define route without using configuration
It either added to
Top of controller with not changing pattern
Top action method with pattern and parameters
It can defined with Get and Post attribute also
Q24. What does following route means HttpGet(“{id}/Edit”})?

Answer :

It means the url which will generate equivalent of http://url.com/2/edit

Q25. What is async Task<action> in mvc?

Answer :

The Task Parallel Library (TPL) does not consume threads in the way you seem to think it does. Tasks are not threads; they are a wrapper around some unit of computation. The task scheduler is responsible for executing each task on any thread that is not busy. At runtime, awaiting a task does not block the thread; it merely parks the execution state so that it may proceed at a later time.

Normally, a single HTTP request would be handled by a single thread, completely removing that thread from the pool until a response is returned. With the TPL, you are not bound by this constraint. Any request that come in starts a continuation with each unit of computation required to calculate a response able to execute on any thread in the pool. With this model, you can handle many more concurrent requests than with standard ASP.Net

Q26. What is partial View in Mvc?

Answer :

It is part of View
It is not directly used by action method
It has underscore before name
Q27. How to call Partial View Inside the view?

Answer :

By using method @html.Partial
By passing Parameter PartialViewname and Model.
Example
@html.Partial(“_PartialView”, Model);
Q28. What is View Component?

Answer :

It is Introduced in MVC 6
It Requires Viewcompenet after class name
Or attribute at top of class [ViewCompoenent]
Primarily used to display component which doesn’t have relationship round it
example
Displaying List most searched word on site on all pages

It needs to inherited from Viewcompenent class
Q29. What are step to Create View component?

Answer :

Class with Logic Naming as XYZViewCompenent
Inherit from Viewcompenent class
Create View for View Component Either in View folder relevant Or Shared folder
the folder name should be Component and Exact Name of View component folder and in the folder require view should be created otherwise it may create issue
Q30. Explain Layout page?

Answer :

It just like master page in MVC
It has 2 important tags @RenderBody() and @Rendersection()
@Renderbody will render the view inside it which where is called
@Rendersection will display the section if defined
Q31. How define section if we want use in MVC?

Answer :

In content page example Home.cshtml
@section Section_Name {
}
Q32. How do MVC find out how to use _layout page?

Answer :

It defined in _ViewStart Page
@{
Layout =”_Layout”
}
Q33. How to invoke component in View Page?

Answer :

@Compenent.MethodName(Parameter if defined).

Q34. Explain basic life cycle of MVC?

Answer :

Life Cycle of MVC can be defined in 2 ways
Application Lifecycle
Request Lifecycle
Application Lifecycle
It consist of only 2 Event
Application start and Application end both depend on IIS.
Request Lifecycle
It starts with
Request
Routing
Controller initialization
Action Execution
Result Execution
Result Filter
Response
Q35. What is Request cycle difference between MVC and Webform?

Answer :

In Webform it Generally calling of page it depends on physical file
In MVC it can logical construct
Both MVC and Webform used httphandler to handle request
Q36. Explain application start event in MVC?

Answer :

An event that fires when first request is received
Can be used to run initial configuration code
protected void Application_Start()
{
AreaRegistraion.RegisterAllAreas();
FilterConfig.RegisterGlobalFilers(Global.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.ReqgisterBundles(BundlesTable.Bubdles);
}
Q37. How MVC find out what route to use for reaching resource ?

Answer :

First route is Registered in MC route table
Public static void RegisterRoutes(RouteCollection routes){
route.MapRoute(name : “XYZ” ,
url:”{ccontroller}/{action}/{id}”,
defualts : new{ controller =”Home”, action “Index”, id=UriParametter.Optional);
}
Then RegisterRoutes  is added in Application_Start event in global.asax
Q38. Explain Application End event in MVC?

Answer :

It fires when application ends
There is no guarantee that it will fire when application crashes
This good place to perform task if something is needed to be done before application shuts up.
Q39. What Route handler class is used in MVC?

Answer :

Basically it has only one purpose, to get right http handler for the request.
Http handler will execute and generate response for request
Maproute method in MVC is extension method which associated with route handler
Q40. How Register Http Module in MVC?

Answer :

We can register module on PreApplicationStart event
It registered at assembly level
[assembly: PreApplicationStartMethod(typeof(className), “Methodname”)]
The above attribute should be added at top name space and below using statement
HttpApplication.RegisterModule(typeof(“Assembly_name_which_perform_action”)] should be under method name
Q41. Explain details of Request Life Cycle of MVC ?

Answer :

There are 10 steps to each request
Begin Request
Authenticate Request
Authorize Request
Resolve Request Cache
Map Request Handler
Acquire Request State
Request handler Execute
Update Request Cache
Log Request
End Request
Q42. In Request event where Routing is read?

Answer :

In Resolve Request Cache event the Routing is determined.

Q44. What is HttpHandler?

Answer :

It was there from asp.net
HttpHandler class implement IHttpHandler
Classes that implement IHttpHandler and generate a response to an HttpRequest
In MVC life cycle they are executed at maprequestHandler and Requesthandler execute event
It used handle extension such .aspx,.cshtml etc
Q45. How Create HttpHandler?

Answer :

By implementing IHttpHandler on Class
Register HttpHandler to Code or in web.config
have 2 Members
IReuseable
ProcessRequest
Q46. Explain Http module?

Answer :

Classes are implemented using IHttpmodule
This are designed to Life Cycle event
Module can implemented in different part of request cycle
What can be done httpmodule can be done in Global.asax file
Q47. How to Create Httpmodule?

Answer:

Implement interface IHttpmodule on class
Register httpmodule to code or web.config
IHttpModule exposes to Members
Init
dispose
Q48. Explain Controller in MVC?

Answer :

Controller are responsible for relationship between view and Model
It implement IController interface
IController exposes on very important method that is Execute
Controller handling occurs in MVCHandler ProcessRequest part in Life cycle
Q49. Explain Controller Life Cycle in MVC?

Answer :

Incoming request is handled by MVCHandler Process Request
Inside MVCHandler there is processRequestInit()
Processinint () calls Controller factory which collect information of handler located at Route table.
Once Controllerfactory collected the information it calls Controller Activation.
Once Controller activation is called It calls Dependency of controller.
After everything goes well it calls Controller.execute()
Q50. Explain Controller factory?

Answer :

It primary responsibility is provide right controller for execution
It implements IControllerFactory interface
The most important method is CreateController
The two method are GetControllerSessionStateBehaviour,ReleaseController
Controller factory have access to dependency resolver
Q51. Explain dependency resolver in Mvc ?

Answer :

IDependencyResolver is interface used for implementation
It was introduced in Mvc in 3.0
It is mostly used IControllerFactory
It exposes 2 method GetService and GetServices
Q52. What is execution flow of action method?

Answer :

Following execution flow of action method

Controller executed
Authentication Filters
Authorization Filters
Model Binding
Action Filter
Action method executed
Action Filters
Q53. Explain Action invoker?

Answer :

Action invoker used by controller to locate and execute action method
Action invoker empowers controller execute method
Action invoker is get implemented by IActionInvoker interface
Method used in interface InvokeAction
Q54. What is action selector?

Answer :

Following are most common action selector
HttpGet
HttpPost
AcceptVerbs
ActionName
NoAction
Custom

Q55. How create and implement Action Method selector?

Answer :

By implementing abstract class ActionMethodSelectorAttribute
It exposes bool method IsValidForRequest
Defined logic and just send across true or false.
False would be rejection for action selector
To mark any method for selector [Class_name_where Action_method_selector_attribute_had_been_implementd] on the top of method
Q56. What is model binding?

Answer :

It process where parameter of action method is mapped to filed on html
It occurs after Authorization in mvc
The default data providers are
Form Data
Route Data
Query String
Files
Custom
It is Implemented using IModelBinder Interface
It exposes Bindmodel method
Q57. Explain Filters in MVC?

Answer :

Filters can run at multiple point in Mvc life cycle
Filter are designed to inject miscellaneous logic in mvc life cycle
There are probably 5 types of filter in MVC
Authentication
Authorization
ActionFilter
ResultFilter
ExceptionFilter
Q58. What would be order of execution of filter if we have more than one filter defined ?

Answer :

Most common is Top to bottom , but it cannot be confirmed
MVC provide parameter which help in defining execution order
It valid for OnActionexecution but not on OnActionExecuted
Q59. Explain Action Life Cycle?

Answer :

Following is life cycle of Action Invoker

ResultFilter On result executing
Execute result
Then based on need either it calls View engine , or It calls write Response
Result Filters On Result executed
Q60. How Create Custom Action Results?

Answer :

Inherit the class with ActionResult Abstract class
Implement ExecuteResult method from ActionResult class
Define the logic in ExecuteResult
Response.write at the end of method
In Controller implement the method with ActionResult
Q61. What is View Life Cycle?

Answer :

Following in life cycle of View engine

ViewResultBase – ExecuteResult()
viewResult – FindView()
Viewengine – FindView()
ViewEgineResult
View – Render()
Q62. How is View implement in MVC?

Answer :

It is exposed by IViewEngine
Following method is exposed
FindView
FindPartialview
ReleaseView
Q63. Explain Katana in MVC ?

Answer :

Katana is used to provide light weight piece of software that can be used to build web application, website, web api etc .
Katana features highly modular compartmentized
It helps in adding feature which is needed in project
It is build of specification of Owin
Q64. What is Owin?

Answer :

It is Open web Interface for dotnet
Katana is implementation of Owin
Owin is specification
Q65. Explain Katana implementation?

Answer :

Add console project
Install-packages Microsoft.Owin.Hosting
It adds Owin , Microsoft.Owin,Microsoft.Owin.Hosting
Install another package Microsoft.Owin.Host.HttpListener
Now add Class Startup
In startup, add method Configuration(IAppBuilder application)
IAppBuilder is part of Owin assembly
application.run is used to run application which process request which it receives.
In run method run.response.writeAsync(“hello world”)
Now in static class
using(WebApp.Start<Startup>(uri))
{
}
Uri is any http://localhost:portnumber you want work on.
Q66. Explain App Func in Katana?

Answer :

Application function is how process interact with the Request by providing delegate Func<IDictonary<string,object>,Task>;
Delegate has its own implementation
public async Task Invoke(IDictonary<string,object> environment)
{
await nextcomponent(environment)
}
Q67. Example for App function or middle ware in Katana?

Answer :

Define alias for App function at the top of class
using Appfunc = Func<IDictonary<string,object>,Task>;
Create class for component
Public class TestWorldComponent {
Appfunc _next
public TestWorldComponent (Appfunc next)
{
_next = next;
}
public task Invoke(IDictonary<string,object> env)
{
var response = env[“owin.ResponseBody] as Stream;
using(var writer = new StreamWriter(Response))
{
return write.writeAsync(“Hi!”);
}
}
}
now in config function of Startup class
app.Use<TestWorldComponent >()
Q68. How to Create Web Api in Katana?

Answer :

Install-package Microdoft.AspNet.WebApi.OwinSelfHost
Create class with name ending with controller with inherited with ApiController
In startup class create method and pass IAppbuilder
ConfigApi(app)
In new method config
add
var config= new HttpConfiguration();
config.Routes.MapHttproute(“name”,”api/{controller}/{id}”, new {id =
RouteParameter.Optional});
app.UseWebApi(config);
Q69. How to associate Katana in IIS?

Answer :

Install Microsoft.Owin.Host.SystemWeb
Convert you Katana project to dll Library Type
IIS except to find dll in bin directory
Now Go to IIS Express path in cmd then ass /path<Path of Katana bin folder> and then run it will execute the katana application
Q70. What option do you have for Authentication when you click on change Authentication in MVC ?

Answer :

Following are Option available

No Authentication- Allow Anonymous users
Individual User Account- Allows Form Authentication ,Can also allow facebook, Microsoft , etc
Organizational Account- Mostly account such Fid (functional id) , Active directory ,Federation service
Windows Authentication-It Active Directory of company
Q71. What will happen if I delete the .mdf file from App_Data Folder which is created by default, and How to fix the problem?

Answer :

There two answer for the Question:

If mdf file was deleted when solution was running, Then when you restart the solution and run the application mdf will we created and data is any added for testing or otherwise will lost

Now If It had been deleted after solution had been shut down, then it will throw error unable to attach the mdf file.

To resolve go to view menu , select sql server Object ,
Connect local machine
search name of the mdf
select and delete the mdf
and refresh, after Refresh restart Visual studio

Q72. What is Core Identity?

Answer:

It is part of Microsoft.Aspnet.Identity.Core
This assembly define some core abstraction used by the application including interface definition for IUser , IRole
Q73. How to implement Core Identity?

Answer :

There is Assembly Microsoft.AspNet.Identity.EntityFramework
Assembly provides the class for implementation such as IdenityUser, IdentityRole etc
Q74. How to integrate 3rd party login such as Google in MVC?

Answer :

There are predefined configuration in App_Start -> Startup_Auth.cs
Inside the file uncomment app.UseexternalSignInCookie Add app.useGoogleAutheicate()
For other you have to register their site and get the secret keys
Q75. What is bootstrap in Css?

Answer :

It is popular front end toolkit
It provide all needed to create website layout, widget , button etc
Bootstrap is present default in mvc application
Bootstrap.css m boostarp.js are two main file
Q76. How to Create help page for controller in MVC?

Answer :

Microsoft.AspNet.WebApi.HelpPage is assembly which generated help
It is will not be seen in reference dll
To Create document use summary comment
In project Property build tab enable XML documentation
Help page folder there is HelpageConfig.cs, enable config.SetDocumentProvider
Q77. What is action result available for Web Api?

Answer :

Following are action result :

OkResult
NotFoundResult
ExceptionResult
UnAuthorizedResult
BadRequestResult
ConflictResult
RedirectResult
InvalidModelStateResult
They are part of IHTTPActionResult

Q78. How to implement IHttpActionResult in Web Api mvc?

Answer :

Create Action method
If data not found NotFound() method can be used
If data is found OK(Model_class) method can be used
Example
public IHttpActionResult GetData(string id)
{
var data = _data.getById(id)
if(data == null)
{
return NotFound(); }
return OK(data);
}
Q79. Explain CORS in Web API?

Answer :

CORS stand for (Cross origin Resource sharing)
It Allows calling of services on other server
To work it requires , 2 thing
Origin
It is signature which mention from where the request has been raised
Access-Control-Allow-Origin
This reverted back by target server
Q80. How to enable Cross domain communication in web api ?

Answer :

To Enable Install Microsoft.Asp.Net.Web.API CORS package
Either Go in config Config.EnableCors();
Id can be set on Controller [EnableCors(“*”,”*”,”GET”)]
Q81. How to Authenticate with Web Api ?

Answer :

Use Jquery version jquery-1.10.2.js situated in scripts folder
We have get access to Access token, it part of middleware
Code located at Start.Auth.cs
Default path is <url>/token
Example
This in Jquery
var logon = function ()
{
var url = “/Token”;
var data = $(“#userInfo”).serialize();
data = data +”&grant_type=password”;
$.post(url,data)
}
This will return token which need to send each time commutation is made or application will require Auth
Access_Token which received need to send each time header.
For sending access token ajax function is used.
Header is “Authorization : “Brearer” + Acess_token
Q82. What is web socket?

Answer :

It is duplex communication protocol
It keeps connection alive between client and server
Connection is created using WebSocket method
ws is protocol used for communication
onmessage is function which used to get the data from the server
It is not supported by all browser
Q83. What is Signlar ?

Answer :

It is project Created by Microsoft
It can be installed using nuget package
Microsoft.AspNet.SignalR is assembly which gets installed.
Main goal of Signlar communication between browser and application
Connection Support by Signlar are as Follow
WebSocket
Server Send Events
Forever Frame
Long Pooling
Q84. How to setup Signlar?

Answer :

Install package microsoft.aspnet.SignalR
Configure Owin Middle ware app.MapSignalR() which sample can be located at read me file
Create HUB, template found under Web -> Signlar
Add Jquery Signlar, application name script in html file which is located in Script folder
Q85. What are browser link?

Answer :

Browser link help in refresh page without going on to the page
It works if application is debug mode, point to local list or development server
It works with multiple browsers if they are or not set as default.
Underline technology used is Signlar
Q86. What is scaffolding?

Answer:

Scaffolding is a process of having template which can be used many times as wizard.

Q87. Explain Async and Wait word in MVC?

Answer :

Method with async keywords can use an await
Await can suspend an async method
Await can free the calling thread
Execution can resume where it left off
Method marked with Async operator we call Async method
Method should end with Async
Async method return task , we can also return void from the method
Example
static async Task<int> TestAsync()
{
var data = await CallWebService();
return data;
}
Q88. What will happen if we have async keyword in method and await is not defined?

Answer :

Complier will give warning .

Q89. How to implement Async and wait in Action method in MVC?

Answer :

Current implementation is good MVC 4 and above
Add async keyword before action method
Return type should be Task<Return_Type>
await keyword be used before function call in method
Example
public async Task<ActionResult>Index()
{
model.test = await calling_function()
return view(model);
}
Q90. What happens if we create async method and call in other sync method?

Answer :

Async keyword will throw warning if await keyword is not used against the method
The data processing inside the method may or may not show the result expected.
Q91. How run parallel task inside async method?

Answer :

By using await Task.WhenAll method we can ran task parallel in async method

Q92. How define how much system wants to wait for external call such as web service call on async method?

Answer :

We can define by using AsyncTimeout and pass needed value and pass cancellation token in method

Q93. What is cancellation token?

Answer :

Cancelation token , token which passed to async method which inform them if request has been cancelled

Q94. How to define error page based on exception on controller?

Answer :

HandleError is attribute used for give error message or view based on error
Example
HandleError(ExceptionType=typeof(What_ever_error_type), view=”ViewName”)
Q95. What is best away to do unit test on Async action or controller?

Answer :

Use test framework which support async such as MSTest, XUnit
Declare test case async return task from it
Use await keyword in front of action which is going to be called
Example
[TestMethod]
public async Task IndexTest()
{
var controller = new HomeController();
var result = (ViewResult) await controller.Index();
}
Q96. What is asp.net web api?

Answer :

It is asp.net based framework which based on build http based services and client
It is build top of asp.net
It is fully supported and extensible framework for building HTTP based endpoints
Available via Nuget
Q97. Why to use Asp.net web api?

Answer :

It is good for commutating with server using ajax.
It can be also exposed to other system
Q98. Is Asp.net API is Restful Service?

Answer :

The Asp.net Web Api doesn’t dictate an architectural style
However you can build a Restful service on top of it, It doesn’t get in your way if you want to design using the Rest architectural style
Q99. What are the advantages of using ASP.NET Web API?

Answer :

Using ASP.NET Web API has a number of advantages, but core of the advantages are:

It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE etc for all CRUD operations.
Complete support for routing.
Response generated in JSON or XML format using MediaTypeFormatter.
It has the ability to be hosted in IIS as well as self-host outside of IIS.
Supports Model binding and Validation.
Support for OData.
Q100. Can we return view from Web API?

Answer :

Yes and No both.

Yes, we can return Html string which can be used by javascript and rendered
No, as in sense we do with normal MVC
Q101. How we can handle errors in Web API?

Answer :

Below are the list of classes which can be used for error handling –

HttpResponseException
Exception Filters
Registering Exception Filters
HttpError
Q102. How to enable tracing in Web API?

Answer :

To enable tracing place below code in –“Register” method of WebAPIConfig.cs file.
config.EnableSystemDiagnosticsTracing();
Q103. Explain method – “ChallengeAsync” in Web API?

Answer :

“ChallengeAsync” method is used to add authentication challenges to response.

Below is the method  signature –

Task ChallengeAsync(
HttpAuthenticationChallengeContext mytestcontext, CancellationToken                                     mytestcancellationToken

)

Q104. What is “Under-Posting” and “Over-Posting” in Web API?

Answer :

“Under-Posting” – When client leaves out some of the properties while binding then it’s called under – posting.
“Over-Posting” – If the client sends more data than expected in binding then it’s called over-posting.
Q105. What is dependency injection?

Answer :

Dependency injection is a software design pattern that allows the removal of hardcoded dependencies and makes it possible to change them whether run-time or compile time.
It creates loosely coupled application
Few of concept used in dependency injection are as follow
Constructor injection
Property injection
Method injection
Q106. What is advantage of Loosely couple Code?

Answer :

Following are advantages of loosely couple code

Extensibility
Testability
Late binding
Parallel development
Maintainability
Q107. What is Life Time Manager in DI container such as Unity?

Answer :

It means Singleton implementation
First time framework will provide instance directly from next time it will provide what is stored
In short it same instance all time
Q108. What Transient manager in DI container?

Answer :

It is opposite of Singleton, each time Repository is mapped it new instance.

Q109. What is easiest way to implement container?

Answer :

This implementation of unity framework
Define container at top of class
IUnityContainer Container ;
Define Configuration
public void configContainer()
{
Container = new UnityContainer();
Container.RegisterType<IInterface,InterafaceImplemnataion>();
}
Use resolver to access the information
Container.Resolve<ImplemnataionName>();
Q110. How use XML for loading configuration using DI container?

Answer :

This implementation of unity framework
Define container at top of class
IUnityContainer Container ;
Define Configuration
public void configContainer()
{
Container = new UnityContainer();
Container.LoadConfiguration();
}
LoadConfiguration says to unity framework to find configuration in XML.
In XML
In configsection define section
<section name =”unity”>
type = “Microsoft.Practice.Unity.Configuration.UnityConfiguration, Microsoft.Practice.Unity.Configuration.Unity”/>
Now define Unity container
Example
<unity>
<namespace name = “nameScape_Of_Assembly”/>
<container>
<register type =”Interface_Name” mapTo =”Implemented_Assembly_Name”/>
</register>
</container>

In this article, we have kept the most asked Asp.Net MVC Interview Questions with their answers to it. So that you can crack the interview with ease.
public static byte[] CreateHTMLtoPDF(string HtmlString) { var htmlContent = String.Format(HtmlString); var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter(); htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape; //var Orientation = new NReco.PdfGenerator.HtmlToPdfConverter().Orientation=NReco.PdfGenerator.PageOrientation.Landscape; htmlToPdf.Size = NReco.PdfGenerator.PageSize.A4; //htmlToPdf.Zoom = -0.55f; var pageMargin = new NReco.PdfGenerator.HtmlToPdfConverter().Margins; //htmlToPdf.PageHeight= 210; //htmlToPdf.PageWidth = 297; pageMargin.Left = 25; pageMargin.Right = 25; pageMargin.Bottom = 25; pageMargin.Top = 25; var pdfBytes = htmlToPdf.GeneratePdf(htmlContent); byte[] bytes; using (MemoryStream input = new MemoryStream(pdfBytes)) { using (MemoryStream output = new MemoryStream()) { string userpassword = "123";//Change it with User DOB Format dd-MM-yyyy string Ownerpassword = "123";//Change it with whatever owner is wanted PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, userpassword, Ownerpassword, PdfWriter.ALLOW_SCREENREADERS); bytes = output.ToArray(); //Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf"); //Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.BinaryWrite(bytes); //Response.End(); } } return bytes; } <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendOTP.aspx.cs" Inherits="Shoping_Cart.SendOTP" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>How to Send and Verify OTP On Mobile No Using C# In Asp.Net</title> </head> <body> <form id="form1" runat="server"> <div> Mobile No: <asp:TextBox ID="txtMobileNo" runat="server" Width="200px"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send OTP" /> <br /> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </div> </form> </body> </html> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Shoping_Cart { public partial class SendOTP : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { try { Random r = new Random(); string OTP = r.Next(1000, 9999).ToString(); //Send message string Username = "youremail@domain.com"; string APIKey = "YourHash"; string SenderName = "MyName"; string Number = "981111111"; string Message = "OTP code is - " + OTP; string URL = "http://api.minifycode.in/send/?username=" + Username + "&hash=" + APIKey + "&sender=" + SenderName + "&numbers=" + Number + "&message=" + Message; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(resp.GetResponseStream()); string results = sr.ReadToEnd(); sr.Close(); Session["OTP"] = OTP; //Redirect for varification Response.Redirect("VerifyOTP.aspx"); } catch (Exception ex) { lblMessage.Text = ex.Message.ToString(); } } } } <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Verify.aspx.cs" Inherits="Cart.VerifyOTP" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Verify OTP</title> </head> <body> <form id="form1" runat="server"> <div> OTP: <asp:TextBox ID="txtOTP" runat="server" Width="200px"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Verify OTP" /> <br /> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </div> </form> </body> </html> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Cart { public partial class OTP : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (Session["OTP"].ToString() == txtOTP.Text) { lblMessage.Text = "You have enter correct OTP."; Session["OTP"] = null; } else { lblMessage.Text = "Pleae enter correct OTP."; } } } }