Building a RESTful API with NancyFx v2
Building a RESTful API with NancyFx v2
The NancyFx v2 official release is available in Nuget since april 2019. The primary reason for upgrading NancyFx to v2 is because of its support for .NETStandard 2.0 which means you can move to .NET Core.
Starting from my previous post Building a RESTful API with NancyFx, I will show you how to upgrade to NancyFx v2.
The full list, though short, of breaking changes can be found at:
The most glaring breaking changes are with "Routing" and "Authentication and security".
Routing
Routing syntax has changed to Get("/", args => "Hello World");, these can be made async by adding the async/await keywords.
To avoid changing the syntax for old routes and modules, Derek Comartin created a new module that would add back the existing routing behavior by calling the new underlying methods in the NancyModule, for more details see:
Just simply extend NancyV1Module instead of NancyModule:
public class PersonModule : NancyV1Module
{
public PersonModule() : base("rest/person")
{
...
Get[""] = GetAllAction;
Get["{id:int}"] = GetAction;
Post[""] = AddAction;
Put["{id:int}"] = ModifyAction;
Delete["{id:int}"] = DeleteAction;
}
private dynamic GetAllAction(dynamic parameters)
{
return PersonRepository.Instance.GetAll();
}
...
}
Authentication and security
public class UserIdentity : ClaimsPrincipal { internal const string HANDLEPERSON_PERMISSION = "HandlePerson"; public string UserName { get; private set; } public Guid UserIdentifier { get; private set; } public UserIdentity(string userName, Guid userIdentifier, IEnumerable<string> claims) { UserName = userName; UserIdentifier = userIdentifier; List<Claim> claimList = new List<Claim>(); foreach (string claim in claims) { claimList.Add(new Claim(ClaimTypes.Role, claim)); } AddIdentity(new ClaimsIdentity(claimList, "Basic")); } public bool HasClaim(string claim) { return Claims.Any(c => c.Value == claim); } }
NancyFx v2 allows you to enforce security at a module or at a route level:
public class PersonModule : NancyV1Module { public PersonModule() : base("rest/person") { this.RequiresAuthentication(); this.RequiresClaims(c => c.Value == UserIdentity.HANDLEPERSON_PERMISSION);
... } ... }
The source code can be found on GitHub at:
Comments
Post a Comment