Unauthorised webapi call returning login page rather than 401

Brock Allen has a nice blog post on how to return 401 for ajax calls when using Cookie authentication and OWIN. http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/ Put this in ConfigureAuth method in the Startup.Auth.cs file: app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString(“/Account/Login”), Provider = new CookieAuthenticationProvider { OnApplyRedirect = ctx => { if (!IsAjaxRequest(ctx.Request)) { ctx.Response.Redirect(ctx.RedirectUri); … Read more

EntityType ‘IdentityUserLogin’ has no key defined. Define the key for this EntityType

In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class’s OnModelCreating: protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // I had removed this /// Rest of on model creating here. } Which then fixed up my missing … Read more

How to extend available properties of User.Identity

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so: public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, … Read more

What is ASP.NET Identity’s IUserSecurityStampStore interface?

This is meant to represent the current snapshot of your user’s credentials. So if nothing changes, the stamp will stay the same. But if the user’s password is changed, or a login is removed (unlink your google/fb account), the stamp will change. This is needed for things like automatically signing users/rejecting old cookies when this … Read more

MVC5 – How to set “selectedValue” in DropDownListFor Html helper

When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option. Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. … Read more

Why map special routes first before common routes in asp.net mvc?

The routing engine will take the first route that matches the supplied URL and attempt to use the route values in that route. The reason why this happens is because the RouteTable is used like a switch-case statement. Picture the following: int caseSwitch = 1; switch (caseSwitch) { case 1: Console.WriteLine(“Case 1”); break; case 1: … Read more