Category Archives: .NET

.NET Core 2.1 is Returning JSON with Lowercase Properties

Hi everyone,

Just testing out .Net Core 2.1 and noticed that all of my JSON properties are being returned in lowercase despite being defined as uppercase. It turns out that this is configurable:

// Change from this

// To this
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

Check out these links for more info:


Dynamic Robots.txt with Web Api 2

Hi everyone,

For a project I’m currently working on I needed a dynamic robots.txt. Because our test environment is public facing we want to keep it from being indexed by Google etc. It took a bit of Googling to find a solution that worked, but in the end it was actually pretty simple.

Here’s the action in one of the API Controllers:

    public class UtilitiesController : CustomBaseApiController
        public HttpResponseMessage GetRobotsFile()
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            var stringBuilder = new StringBuilder();

            if (Helpers.IsProduction())
                // Allow bots in production
                stringBuilder.AppendLine("user-agent: *");
                stringBuilder.AppendLine("disallow: ");
                // Don't allow bots in non-production environments
                stringBuilder.AppendLine("user-agent: *");
                stringBuilder.AppendLine("disallow: *");

            resp.Content = new StringContent(stringBuilder.ToString());

            return resp;

Also need to add the following to your web.config so that the robots.txt file can processed by the routing handler. Without this IIS will attempt to serve it as a static file and will return a 404 when it’s not found:


In production you’ll end up with the following:

user-agent: *

And any other environments:

user-agent: *
disallow: *

Thanks to these answers on stackoverflow for the info:

DbSet does not contain a definition for ‘FromSQL’ and no extension method ‘FromSql’ accepting an argument of type ‘DbSet’ could be found.

Hi everyone,

I ran into the following error while attempting to use a custom query with EntityFramework:

DbSet does not contain a definition for ‘FromSQL’ and no extension method ‘FromSql’ accepting an argument of type ‘DbSet’ could be found.

This one’s pretty straight forward:

// Install the following package via nuget
Install-package Microsoft.EntityFrameworkCore.Relational

//Add the following namespace to your file
using Microsoft.EntityFrameworkCore;

Hopefully that’ll solve it for you, but if not there’s a lot a more information in these posts:

Include UserId in Login Response (Token) – Web API 2

Hi everyone,

A quick post on how to include the user’s id in your login response when using Web API 2.

The default response to the /Token request is as follows:

“access_token”: “xxxxxxxxxxxxx_xxxx”,
“token_type”: “bearer”,
“expires_in”: 1209599,
“userName”: “”,
“.issued”: “Mon, 23 Apr 2018 06:08:03 GMT”,
“.expires”: “Mon, 07 May 2018 06:08:03 GMT”

Once the changes below have been made the response will include a userId field:

“access_token”: “xxxxxxxxxxxxx_xxxx”,
“token_type”: “bearer”,
“expires_in”: 1209599,
“userName”: “”,
“.issued”: “Mon, 23 Apr 2018 06:08:03 GMT”,
“.expires”: “Mon, 07 May 2018 06:08:03 GMT”,
“userId”: “xxxxxxx”

There are three very small changes required in order to add this functionality.

First, add an additional argument to CreateProperties in ApplicationOAuthProvider.cs

public static AuthenticationProperties CreateProperties(string userName, string userId)
IDictionary data = new Dictionary
{ "userName", userName },
// Add
{ "userId", userId }
return new AuthenticationProperties(data);

Pass userId to CreateProperties in ApplicationOauthProvider.

// ApplicationOAuthProvider.cs > GrantResourceOwnerCredentials
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,

// Add user id
AuthenticationProperties properties = CreateProperties(user.UserName, user.Id);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

Pass userId to CreateProperties in AccountController.

// AccountController.cs > GetExternalLogin
if (hasRegistered)

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,

// Add userid
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName, user.Id);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

Cannot attach the file ‘C:…database.mdf’ as database x – Entity Framework

Hi everyone,

I ran into the following error when attempting to run ‘update-database’ on an initial migration:

Cannot attach the file ‘C:Users…App_Dataaspnet-…115933.mdf’ as database ‘aspnet-…15933’

The solution to this one is pretty easy, remove the initial catalog property from your connection string.

…33.mdf;Initial Catalog=aspnet…

This is apparently caused by issues with EntityFramework and multiple projects in the same database. See the following stackoverflow answer for more info:

Retrieving User Id in Web API 2 Controller – .NET

Hi everyone,

Just a quick post on how to retrieve the current user’s id in a Web API 2 controller:

var userId = RequestContext.Principal.Identity.GetUserId();

Note that you’ll need the following using statements:

using Microsoft.AspNet.Identity;
using System.Web.Http;

Thanks to the following stackoverflow post for the info: