Skip to content

Instantly share code, notes, and snippets.

@khalidabuhakmeh
Created September 16, 2018 17:20
Show Gist options
  • Save khalidabuhakmeh/6df565f0e24991d47b4027eeb0cbed3e to your computer and use it in GitHub Desktop.
Save khalidabuhakmeh/6df565f0e24991d47b4027eeb0cbed3e to your computer and use it in GitHub Desktop.
ASP.NET Core Bound<T> Concept
/*
I wish ASP.NET Core had the concept of a `Bound` class. The Bound
class would be accessible to developers and be hydrated by the model binder to not only give
you the value the caller sent, but allow you to understand if the user expressed the intent
to give you that information.
There are multiple reasons why a value may not have been bound:
1. Failed Deserialization
{ "number" : "this is not a number" }
2. User Never Sent It
{ "number" : null }
3. The Consumer of the API (Another Developer) Forgot to Send it.
{}
*/
public class Bound<T> {
/* properties */
public bool IsAvailable => Result == BindingResults.Available;
public bool IsBindingFailed => Result == BindingResults.BindingFailed;
public bool IsUnavailable => Result == BindingResults.Unavailable;
// Unavailable, BindingFailed, Available, etc.
public BindingResults Result {get;}
public T Value {get;}
public string OriginalValue {get;}
}
public class ContactUsRequest {
// added in version 1
public Bound<string> FullName {get;set;}
// added in version 2
public Bound<string> FirstName {get;set;}
public Bound<string> LastName {get;set;}
}
/* How Would You Use It? */
/* 1. In an Action */
public IActionResult Post(ContactUsRequest request)
{
if (request.FullName.IsAvailable)
{
// old version, let's split it
var parts = request.FullName.Split(' ');
request.FirstName = parts.FirstOrDefault();
request.LastName = parts.LastOrDefault();
}
/* continue on */
}
/* 2. In an ActionAttribute */
- If the action argument looks a certain way, change it before it gets to the action
/* 3. At the Routing Level */
- Reroute to a completely different action based on binding outcome
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment