Skip to content
This repository has been archived by the owner on Jan 24, 2021. It is now read-only.

Nancy v2 Upgrade Notes

Andreas Håkansson edited this page Apr 1, 2016 · 14 revisions

Overview

Context.CurrentUser ClaimsPrincipal Mapping to Domain Object

In Nancy 1.x versions Context.CurrentUser was a IUserIdentity, you could add properties to your implementation and then access these properties that were not on the interface by casting eg. var customerId = ((MyUser)Context.CurrentUser).CustomerId;

In v2.x of Nancy Context.CurrentUser is a ClaimsPrincipal. By default this contains an array of claims that the user has. So to get a name value for example you would have do something like Context.CurrentUser.FindFirst(ClaimTypes.Name).Value Not very elegant and what about the User object you already had in 1.x . The best way to do this is to tweak the User object and use an extension method to cast it from ClaimsPrincipal to your User object.

public class MyPrincipal : ClaimsPrincipal
{
   public MyPrincipal(IPrincipal principal) : base(principal)
   {
   }

   public string FullName => FindFirst(ClaimTypes.Name).Value;
}

public static class PrincipalExtensions
{
   public static MyPrincipal AsMyPrincipal(this IPrincipal principal)
   {
       if (principal != null)
       {
           return principal as MyPrincipal
               ?? new MyPrincipal(principal);
       }

       return null;
   }
}

public class HomeModule : NancyModule
{
    public HomeModule()
    {
        Get["/] = (parameters, token) =>
        {
            var user = Context.CurrentUser.AsMyPrincipal();
            return Task.FromResult<dynamic>(user.FullName);
        };
    }
}

Bootstrapper DiagnosticsConfiguration

In Nancy v2 there is a whole new configuration API. This is now handled in the bootstrapper by overriding the Configure method. For Diagnostics you can use it like so:

public override void Configure(Nancy.Configuration.INancyEnvironment environment)
{
    base.Configure(environment);
    environment.Diagnostics(Password: "vqportal!");
}

Bootstrapp InternalConfiguration

This has a different signature but now takes in a ITypeCatalog argument. If you are using the WithOverrides API this should still work, you just need to change the method signature:

protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration
{
     get
     {
         var processors = new[] { typeof(JsonProcessor) };
         return NancyInternalConfiguration.WithOverrides(x => x.ResponseProcessors = processors);
     }
}

Nancy.Serializers.Json.ServiceStack Renamed

This namespacehas been renamed to Nancy.Serialization.ServiceStack

DefaultResponseFormatter constructor change

One of the arguments was previously an array of ISerializer, this is now a ISerializerFactory

Clone this wiki locally