EzDevInfo.com

asp.net-mvc-4 interview questions

Top asp.net-mvc-4 frequently asked interview questions

What is new in asp.net mvc 5 [closed]

Today on twitter I saw a tutorial for ASP.NET MVC 5. I didn't know it existed.

So, what are the new, cool features of MVC 5? What are the biggest differences compared to MVC 4?


Source: (StackOverflow)

Styles.Render in MVC4

In a .NET MVC4 project how does @Styles.Render works?

I mean, in @Styles.Render("~/Content/css") which file is it calling?

I dont have a file or a folder called "css" inside my Content folder.


Source: (StackOverflow)

Advertisements

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

I wish to add an ASP.NET Web API to an ASP.NET MVC 4 Web Application project, developed in Visual Studio 2012. Which steps must I perform to add a functioning Web API to the project? I'm aware that I need a controller deriving from ApiController, but that's about all I know.

Let me know if I need to provide more details.


Source: (StackOverflow)

ASP.NET 4.5 has not been registered on the Web server

In my Win 7 development machine, and in order to use SQL Express instance instead of the localDB installed by default. I unchecked "Use IIS Express" in my MVC 4 project properties page (Web tab), then I got the following error:

ASP.NET 4.5 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5 in order for your site to run correctly.

I verified that ASP.NET is activated within the IIS features.

Please what could be done to resolve this?


Source: (StackOverflow)

What is the _references.js used for?

What is the _references.js file used for in a new ASP.NET MVC 4 project?


Source: (StackOverflow)

How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

I'm trying to use the new bundling feature in a project I recently converted from MVC 3 to MVC 4 beta. It requires a line of code in global.asax, BundleTable.Bundles.RegisterTemplateBundles();, which requires using System.Web.Optimization; at the top.

When I do this, I get the red squiggly lines that say, "Are you missing an assembly reference?" When I try and add reference, and click on the .NET tab in the dialog, sort from A-Z, I do not see System.Web.Optimization.

How do I add this ref to my project? Thanks.


Source: (StackOverflow)

How do I set a cookie on HttpClient's HttpRequestMessage

I am trying to use the web api's HttpClient to do a post to an endpoint that requires login in the form of an HTTP cookie that identifies an account (this is only something that is #ifdef'ed out of the release version).

How do I add a cookie to the HttpRequestMessage?


Source: (StackOverflow)

InvalidCastException is thrown after installing ASP.NET MVC 4 Beta

I get the following exception after installing ASP.NET MVC 4 Beta on a machine with ASP.NET MVC 3.

System.InvalidCastException was unhandled by user code Message=[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Source=System.Web.WebPages.Razor

StackTrace:

at System.Web.WebPages.Razor.WebRazorHostFactory.GetRazorSection(String virtualPath) at System.Web.WebPages.Razor.WebRazorHostFactory.CreateHostFromConfig(String virtualPath, String physicalPath) at System.Web.WebPages.Razor.RazorBuildProvider.GetHostFromConfig() at System.Web.WebPages.Razor.RazorBuildProvider.CreateHost() at System.Web.WebPages.Razor.RazorBuildProvider.EnsureGeneratedCode() at System.Web.WebPages.Razor.RazorBuildProvider.get_CodeCompilerType() at System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider) at System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders() at System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound) at System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.FileExists(String virtualPath) at System.Web.Mvc.BuildManagerViewEngine.FileExists(ControllerContext controllerContext, String virtualPath) at System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName(ControllerContext controllerContext, List`1 locations, String name, String controllerName, String areaName, String cacheKey, String[]& searchedLocations) at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations) at System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache) at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClassc.b__b(IViewEngine e) at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths) at System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName) at System.Web.Mvc.ViewResult.FindView(ControllerContext context) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<>c__DisplayClass1e.b__1b() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at [project_namespace].Controllers.GlobalizationController.ExecuteCore() in [file_path] at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.b__5() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.b__d() at System.Web.Mvc.SecurityUtil.b__0(Action f) at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

This blocks me completely and while I would like to keep the beta, I might need to remove it completely in order to get rid of the exception.


Source: (StackOverflow)

How to create ASP.NET Web API Url?

In ASP.NET MVC, we have @Url.Action for actions. Is there something similar like @Url.Api which would route to /api/controller?


Source: (StackOverflow)

Why use @Scripts.Render("~/bundles/jquery")

How does @Scripts.Render("~/bundles/jquery") differ from just referencing the script from html (ie <script src="~/bundles/jquery.js" type="text/javascript"></script>)? Are there any performance gains?


Source: (StackOverflow)

ValidateAntiForgeryToken purpose, explanation and example

Could you explain ValidateAntiForgeryToken purpose and show me example about ValidateAntiForgeryToken in MVC 4?

I could not find any examples which explain this attribute?


Source: (StackOverflow)

How to "warm-up" Entity Framework? When does it get "cold"?

No, the answer to my second question is not the winter.

Preface:

I've been doing a lot of research on Entity Framework recently and something that keeps bothering me is its performance when the queries are not warmed-up, so called cold queries.

I went through the performance considerations article for Entity Framework 5.0. The authors introduced the concept of Warm and Cold queries and how they differ, which I also noticed myself without knowing of their existence. Here it's probably worth to mention I only have six month of experience behind my back.

Now I know what topics I can research into additionally if I want to understand the framework better in terms of performance. Unfortunately most of the information on the Internet is outdated or bloated with subjectivity, hence my inability to find any additional information on the Warm vs Cold queries topic.

Basically what I've noticed so far is that whenever I have to recompile or the recycling hits in, my initial queries are getting very slow. Any subsequent data read is fast (subjective), as expected.

We'll be migrating to Windows Server 2012, IIS8 and SQL Server 2012 and as a Junior I actually won myself the opportunity to test them before the rest. I'm very happy they introduced a warming-up module that will get my application ready for that first request. However, I'm not sure how to proceed with warming up my Entity Framework.

What I already know is worth doing:

  • Generate my Views in advance as suggested.
  • Eventually move my models into a separate assembly.

What I consider doing, by going with common sense, probably wrong approach:

  • Doing dummy data reads at Application Start in order to warm things up, generate and validate the models.

Questions:

  • What would be the best approach to have high availability on my Entity Framework at anytime?
  • In what cases does the Entity Framework gets "cold" again? (Recompilation, Recycling, IIS Restart etc.)

Source: (StackOverflow)

Anti forgery token is meant for user "" but the current user is "username"

I'm building a single page application and experiencing an issue with anti-forgery tokens.

I know why the issue happens I just don't know how to fix it.

I get the error when the following happens:

  1. Non-logged-in user loads a dialog (with a generated anti-forgery token)
  2. User closes dialog
  3. User logs in
  4. User opens the same dialog
  5. User submits form in dialog

Anti forgery token is meant for user "" but the current user is "username"

The reason this happens is because my application is 100% single-page, and when a user successfully logs in through an ajax post to /Account/JsonLogin, I simply switch out the current views with the "authenticated views" returned from the server but do not reload the page.

I know this is the reason because if I simple reload the page between steps 3 and 4, there is no error.

So it seems that @Html.AntiForgeryToken() in the loaded form still returns a token for the old user until the page is reloaded.

How can I change @Html.AntiForgeryToken() to return a token for the new, authenticated user?

I inject a new GenericalPrincipal with a custom IIdentity on every Application_AuthenticateRequest so by the time @Html.AntiForgeryToken() gets called HttpContext.Current.User.Identity is, in fact my custom Identity with IsAuthenticated property set to true and yet @Html.AntiForgeryToken still seems to render a token for the old user unless I do a page reload.


Source: (StackOverflow)

Single controller with multiple GET methods in ASP.NET Web API

In WCF Web API I had a class of similar structure:

public class SomeController : ApiController
{
    [WebGet(UriTemplate = "{itemSource}/Items")]
    public SomeValue GetItems(CustomParam parameter) { ... }

    [WebGet(UriTemplate = "{itemSource}/Items/{parent}")]
    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}

Since we could map individual methods, it was very simple to get the right request at the right place. For similar class which had only a single GET method but also had an Object parameter, I successfully used IActionValueBinder. However, in the case described above I get the following error:

Multiple actions were found that match the request: 

SomeValue GetItems(CustomParam parameter) on type SomeType

SomeValue GetChildItems(CustomParam parameter, SomeObject parent) on type SomeType

I am trying to approach this problem by overriding the ExecuteAsync method of ApiController but with no luck so far. Any advice on this issue?

Edit: I forgot to mention that now I am trying to move this code on ASP.NET Web API which has a different approach to routing. The question is, how do I make the code work on ASP.NET Web API?


Source: (StackOverflow)

How to pass json POST data to Web API method as object

ASP.NET MVC4 Web API application defines post method to save customer. Customer is passed in json format in POST request body. Customer parameter in post method contains null values for properties.

How to fix this so that posted data will passed as customer object ?

If possible Content-Type: application/x-www-form-urlencoded should used since I dont know how to change it in javascript method which posts form.

Controller:

public class CustomersController : ApiController {

  public object Post([FromBody] Customer customer)
        {
            return Request.CreateResponse(HttpStatusCode.OK,
            new
            {
                customer = customer
            });
        }
    }
}

public class Customer
    {
        public string company_name { get; set; }
        public string contact_name { get; set; }
     }

Request:

POST http://localhost:52216/api/customers HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

{"contact_name":"sdfsd","company_name":"ssssd"}

Source: (StackOverflow)