EzDevInfo.com

asp.net-mvc-5 interview questions

Top asp.net-mvc-5 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)

How to install asp.net mvc 5 in visual studio 2012?

Is there any way to install mvc 5 in visual studio 2012?

I've tried using nuget http://www.nuget.org/packages/Microsoft.AspNet.Mvc But I think that it should come as visual studio extension, cant find that anywhere.

Or it is available only in VS2013?


Source: (StackOverflow)

Advertisements

Visual Studio 2013 IntelliSense stops working for ASP.NET MVC5 Controllers

I am facing a weird problem in my Visual Studio 2013 ASP.NET MVC 5 project. All of a sudden, the IntelliSense in the Controller classes of the MVC 5 project are not working at all.

I have other class library projects in my solution and IntelliSense is working in those class library project files, but the problem is only within the MVC project. Usually these kinds of problems are solved by restarting Visual Studio: not only did I restart Visual Studio, but I also restarted my computer, and the IntelliSense problem is not getting fixed at all.

Are there any other steps that can get me IntelliSense back?


Source: (StackOverflow)

How to add MVC5 to Visual Studio 2013?

I'm starting a new project, and would like to give a try to MVC 5 (I have built a web app using MVC 4 before).

In Visual Studio 2013, I click the New Project and navigate to Visual C# > Web > Visual Studio 2012 (even though I have installed VS 2013 it says 2012 in the menu) and on that list I only have MVC 4 application - not 5.

The framework in the drop down menu is set to .NET Framework 4.5.1 - and still nothing.

I've checked Tools > Extensions and Update and searched for MVC 5 - but it doesn't find anything official from Microsoft.

How can I add MVC 5 to my Visual Studio 2013?

Thank you


Source: (StackOverflow)

ASP MVC5 - Identity. How to get current ApplicationUser

I have Article entity in my project which have ApplicationUser property named Author. How can I get full object of current logged ApplicationUser. While creating new article I have to set Author property in Article to current ApplicationUser.

In old Membership mechanizm it was simple but in new Identity mechanizm I don't know how to do this.

I tried to do this that way:

  • Add using statement for Identity extensions: using Microsoft.AspNet.Identity;
  • Then I try to get current user: ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == User.Identity.GetUserId());

But I get exception :

LINQ to Entities does not recognize the method 'System.String GetUserId(System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store expression. Source=EntityFramework


Source: (StackOverflow)

How can I change the table names when using Visual Studio 2013 AspNet Identity?

I am using the release version (RTM, not RC) of Visual Studio 2013 (downloaded from MSDN 10/18/2013) and therefore the latest (RTM) version of AspNet.Identity. When I create a new web project, I select "Individual User Accounts" for authentication. This creates the following tables:

  1. AspNetRoles
  2. AspNetUserClaims
  3. AspNetUserLogins
  4. AspNetUserRoles
  5. AspNetUsers

When I register a new user (using the default template), these tables (listed above) are created and the AspNetUsers table has a record inserted which contains:

  1. Id
  2. UserName
  3. PasswordHash
  4. SecurityStamp
  5. Discriminator

Additionally, by adding public properties to the class "ApplicationUser" I have successfully added additional fields to the AspNetUsers table, such as "FirstName", "LastName", "PhoneNumber", etc.

Here's my question. Is there a way to change the names of the above tables (when they are first created) or will they always be named with the AspNet prefix as I listed above? If the table names can be named differently, please explain how. Thanks--.

-- UPDATE --

I implemented @Hao Kung's solution. It does create a new table (for example I called it MyUsers) but it also still creates the AspNetUsers table. The goal is to replace the "AspNetUsers" table with the "MyUsers" table. See code below and database image of tables created.

I would actually like to replace each AspNet table with my own name... For Example: MyRoles, MyUserClaims, MyUserLogins, MyUserRoles, MyUsers.

Any ideas on how to accomplish this and end up with only one set of tables?

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }
    public string PhonePrimary { get; set; }
    public string PhoneSecondary { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(): base("DefaultConnection")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("MyUsers");
    }
}

Database Tables

-- UPDATE ANSWER --

Thanks to both Hao Kung and Peter Stulinski. This solved my problem...

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
        modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
        modelBuilder.Entity<IdentityUserRole>().ToTable("MyUserRoles");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("MyUserLogins");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("MyUserClaims");
        modelBuilder.Entity<IdentityRole>().ToTable("MyRoles");
    }

Source: (StackOverflow)

How to get current user, and how to use User class in MVC5?

  • How can I get the id of the currently logged in user in MVC 5? I tried the StackOverflow suggestions, but they seem to be not for MVC 5.
  • Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a User should have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?

I'm using "Individual User Accounts" from the MVC template.

Tried these:

'Membership.GetUser()' is null.


Source: (StackOverflow)

What is ASP.NET Identity's IUserSecurityStampStore interface?

Looking at ASP.NET Identity (new membership implementation in ASP.NET), I came across this interface when implementing my own UserStore:

//Microsoft.AspNet.Identity.Core.dll

namespace Microsoft.AspNet.Identity
{ 
    public interface IUserSecurityStampStore<TUser> :
    {
        // Methods
        Task<string> GetSecurityStampAsync(TUser user);
        Task SetSecurityStampAsync(TUser user, string stamp);
    }
}

IUserSecurityStampStore is implemented by the default EntityFramework.UserStore<TUser> which essentially get and set the TUser.SecurityStamp property.

After some more digging, it appears that a SecurityStamp is a Guid that is newly generated at key points in the UserManager (for example, changing passwords).

I can't really decipher much beyond this since I'm examining this code in Reflector. Almost all the symbol and async information has been optimized out.

Also, Google hasn't been much help.

Questions are:

  • What is a SecurityStamp in ASP.NET Identity and what is it used for?
  • Does the SecurityStamp play any role when authentication cookies are created?
  • Are there any security ramifications or precautions that need to be taken with this? For example, don't send this value downstream to clients?

Update (9/16/2014)

Source code available here:


Source: (StackOverflow)

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

I recently started following this guide to migrate my project to .NET 4.5.1 and Web Api 2.

The very first thing MS developer Rick Anderson asks you to do is change:

WebApiConfig.Register(GlobalConfiguration.Configuration);

to

GlobalConfiguration.Configure(WebApiConfig.Register);

in the global.asax file. Yet this is giving me an error when I try to build:

Error 1 'System.Web.Http.GlobalConfiguration' does not contain a definition for 'Configure'

My project is currently on MVC 5 and Web Api 2 and .NET 4.5.1, yet I think System.Web.Http still thinks it's the .NEt 4.0 version.

How can I go about fixing this?

Thank you.

Edit:

Here are my assembly bindings:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
  </dependentAssembly>
  <!--
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly> -->
</assemblyBinding>

Everything commented out after the top was commented because I was getting the error:

Warning 2 Found conflicts between different versions of the same dependent assembly that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed.

and getting rid of the hard bindings was fixing that.


Source: (StackOverflow)

OWIN: unauthorised webapi call returning login page rather than 401

How do I configure my mvc/webapi project so that a webapi method called from a razor view doesn't return the loginpage when its unauthorised?

Its a MVC5 application which also has WebApi controllers for calls via javascript.

The two methods below

[Route("api/home/LatestProblems")]      
[HttpGet()]
public List<vmLatestProblems> LatestProblems()
{
    // Something here
}

[Route("api/home/myLatestProblems")]
[HttpGet()]
[Authorize(Roles = "Member")]
public List<vmLatestProblems> mylatestproblems()
{
   // Something there
}

are called via the following angular code:

angular.module('appWorship').controller('latest', 
    ['$scope', '$http', function ($scope,$http) {         
        var urlBase = baseurl + '/api/home/LatestProblems';
        $http.get(urlBase).success(function (data) {
            $scope.data = data;
        }).error(function (data) {
            console.log(data);
        });
        $http.get(baseurl + '/api/home/mylatestproblems')
          .success(function (data) {
            $scope.data2 = data;
        }).error(function (data) {
            console.log(data);
        });  
    }]
);

So I'm not logged in and the first method successfully returns data. the second method returns (in the success function) data which contains the equivalent of a login page. i.e. what you would get in mvc if you requested a controller action which was stamped with [Authorize] and you weren't logged in.

I want it to return a 401 unauthorized, so that i can display different data for users based on if they are logged in or not. Ideally if the user is logged in i want to be able to access the Controller's User property so i can return data specific to that Member.

UPDATE: Since none of the suggestions below seem to work anymore (changes to Identity or WebAPI) ive created a raw example on github which should illustrate the problem.


Source: (StackOverflow)

How to set Default Controller in asp.net MVC 4 & MVC 5

How do I set Default Controller for my ASP.NET MVC 4 project without making it HomeController?

How should I setup a default Area when the application starts?


Source: (StackOverflow)

Is ASP.NET MVC 5 incompatible with the WebMatrix SimpleMembershipProvider?

We have an existing application that was build on ASP.NET MVC 4 & Web API. The admin parts of the site use Simple Membership. I'm interested in upgrading the application to MVC 5 / Web API 2, to take advantage of some of the new features that have been added. But it looks like they might be incompatible.

Specifically, after installing the RC packages from NuGet into one of the projects in my solution, and updating the web.config information, the application starts dying during startup on the line that calls WebSecurity.InitializeDatabaseConnection(), with this exception:

[MethodAccessException: Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.OnConnectionOpened(System.Object, WebMatrix.Data.ConnectionEventArgs)' to access security critical method 'System.Web.WebPages.HttpContextExtensions.RegisterForDispose(System.Web.HttpContextBase, System.IDisposable)' failed.]
   WebMatrix.WebData.PreApplicationStartCode.OnConnectionOpened(Object sender, ConnectionEventArgs e) +70
   WebMatrix.Data.Database.OnConnectionOpened() +70
   WebMatrix.Data.Database.EnsureConnectionOpen() +51
   WebMatrix.Data.Database.QueryValue(String commandText, Object[] args) +63
   WebMatrix.WebData.DatabaseWrapper.QueryValue(String commandText, Object[] parameters) +13
   WebMatrix.WebData.SimpleMembershipProvider.GetUserId(IDatabase db, String userTableName, String userNameColumn, String userIdColumn, String userName) +206
   WebMatrix.WebData.SimpleMembershipProvider.ValidateUserTable() +87

Other projects in the same solution using Simple Membership that I have not upgraded continue to work just fine.

Googling around for more information turns up lots of hits for that exception, of course, but nothing particular to WebMatrix.

FWIW: I know that Microsoft has introduced (yet another) membership and identity solution, but unless there's a way to use that with the existing Simple Membership tables, or a seamless migration path for all of our existing user data, that's not really an option for us.

UPDATE (11 Oct)

I just tried this again with a fresh checkout of the current trunk of our app. I'm using Visual Studio 2012, but otherwise followed the instructions from MS for upgrading an existing project. After updating to MVC 5 / Web API 2 / EF 6, the app started up an ran just fine.

There were no explicit trust requirements in the web.config to remove. I added the code from this question to Global.asax.cs, and it reports that the app is running with full trust (in IIS Express, just F5-ed from VS).

Re-adding the same call to InitializeDatabaseConnection(), it starts dying with the exact same exception.

SOLUTION (28 Oct)

Trying the solution in @Kevin's update from Friday, I found that it works. It was really strange to me that adding this apparently unrelated package would solve these security issues, and even more strange after I removed the package from my solution, and it kept working.

Taking a closer look at what was happening, I realized that the reason why this fixes the behavior is quite simple: the Microsoft.AspNet.WebHelpers package has two dependencies that were being added to my solution: Microsoft.AspNet.WebPages.Data and Microsoft.AspNet.WebPages.WebData. Microsoft has moved the WebMatrix classes into new packages.

So added the helpers package fixed the problem, not because of anything it was doing, but because it was causing updated versions of the broken assemblies to be added to my solution. The solution to the initial incompatibility, then, is to install these new packages when updating everything else from NuGet:

Install-Package Microsoft.AspNet.WebPages.WebData

UPDATE (13 May 2015)

It has been suggested to me that you may also need to manually install the second new package:

Install-Package Microsoft.AspNet.WebPages.Data

This should not be necessary, because this package is an explicit dependency of the first, and NuGet should be smart enough to install both. But if you get an error when building, or don't see NuGet add the dependency, it might help you.


Source: (StackOverflow)

MVC5, WebAPI2 and AutoFac not working. All Nuget packages updated

I've updated all of the nuget packages in my project, as well as the AutoFac MVC5 Integration package (removed MVC4 one) and still no dice.

Inheritance security rules violated while overriding member: 'Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.


Source: (StackOverflow)

upgrading from MVC4 to MVC5

I have made that dreadful error of upgrading from MVC4 to MVC5 pre-release by updating the razor, and mvc webpage in my references I have System.Web.Mvc, System.Web.Webpages, System.Web.Webpages.Razor and System.Web.Razor as version v4.0.30319, when I run my application I get

[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=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'.

Type B originates from
'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, 
PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 
'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\membership\c70f06fe\9163b1ca\assembly\dl3\291c956e\73c25daa_cf74ce01\System.Web.WebPages.Razor.dll'.

is this the same as http://www.asp.net/whitepapers/mvc4-release-notes

Thanks

Adding a stacktrace:

[InvalidCastException: [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=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'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location

'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\c70f06fe\9163b1ca\assembly\dl3\291c956e\73c25daa_cf74ce01\System.Web.WebPages.Razor.dll'.]
System.Web.WebPages.Razor.WebRazorHostFactory.CreateHostFromConfig(String virtualPath, String physicalPath) +193
System.Web.WebPages.Razor.RazorBuildProvider.GetHostFromConfig() +51
System.Web.WebPages.Razor.RazorBuildProvider.CreateHost() +24
System.Web.WebPages.Razor.RazorBuildProvider.get_Host() +34
System.Web.WebPages.Razor.RazorBuildProvider.EnsureGeneratedCode() +85
System.Web.WebPages.Razor.RazorBuildProvider.get_CodeCompilerType() +34
System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider) +189
System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders() +265
System.Web.Compilation.BuildProvidersCompiler.PerformBuild() +21
System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +580
System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +571
System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +203
System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound) +249
System.Web.Compilation.BuildManager.GetCompiledType(VirtualPath virtualPath) +17
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +90
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +380
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +109
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +890
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +97
System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Source: (StackOverflow)

OwinStartup not firing

I had the OwinStartup configuration code working perfectly and then it stopped working. Unfortunately I'm not sure exactly what I did to get it to stop working and am having a really hard time figuring it out.

To make sure I have the basics covered, I doubled checked to make sure the I have the

[assembly:OwinStartup(typeof(WebApplication.Startup))] 

attribute assigned properly and made sure that I don't have an appSetting for owin:AutomaticAppStartup that is set to false so I made one set to true to be safe as there was nothing there before.

<add key="owin:AutomaticAppStartup" value="true" />

I also tried specifically calling out the appSetting:

<add key="owin:appStartup" value="WebApplication.Startup" />

Before it stopped working I upgraded the Microsoft.Owin.Security NuGet packages to 2.0.2, so I tried reverting them to 2.0.1 (that was a pain) but it didn't change anything. I have WebActivator installed on the project and am using that to bootstrap other things but I've tested that on a fresh WebApplication template and it works there so I don't think that is the culprit.

I also tried removing my Startup class and using Visual Studio to add a new one using the OWIN Startup Class type in Add New Item and that isn't getting called either. Next I tried adding a second Startup class since I know it will throw an exception if there is more than one OwinStartup attributes defined, but it isn't throwing any exception there.

Not sure what else to try. Any thoughts?

Update

Turns out that Resharper removed the reference to Microsoft.Owin.Host.SystemWeb when I used it to remove unused references.


Source: (StackOverflow)