Skip to content

Instantly share code, notes, and snippets.

@jchannon
Last active March 2, 2016 08:37
Show Gist options
  • Save jchannon/dd8086aaa51ac50a4dcc to your computer and use it in GitHub Desktop.
Save jchannon/dd8086aaa51ac50a4dcc to your computer and use it in GitHub Desktop.
Nancy + problem+json extension using https://www.nuget.org/packages/Tavis.Problem/
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/"] = _ => "Hi";
Post["/"] = _ =>
{
this.ModelValidationResult.Errors.Add("FirstName", "Firstname must start with a Z");
this.ModelValidationResult.Errors.Add("LastName", "Lastname must rhyme with Orange");
return Response.AsHTTPValidationProblem();
};
}
}
{
"type": "http://localhost:1234/validation-error.html",
"title": "Unable to bind incoming data",
"status": 422,
"detail": "Unable to bind incoming data to the expected model",
"validation-errors": [
{
"Key": "FirstName",
"Errors": [
"Firstname must start with a Z"
]
},
{
"Key": "LastName",
"Errors": [
"Lastname must rhyme with Orange"
]
}
]
}
public static class FormatterExtensions
{
public static Response AsHTTPValidationProblem(this IResponseFormatter formatter)
{
var problemDoc = new ProblemDocument
{
ProblemType = new Uri(formatter.Context.Request.Url.ToString() + "/validation-error.html"),
Title = "Unable to bind incoming data",
StatusCode = (System.Net.HttpStatusCode)422,
Detail = "Unable to bind incoming data to the expected model",
};
var errors = formatter.Context.ModelValidationResult.Errors.Select(x => new { Key = x.Key, Errors = x.Value.Select(y => y.ErrorMessage) });
problemDoc.Extensions.Add("validation-errors", JToken.FromObject(errors));
var resp = new Response
{
StatusCode = HttpStatusCode.UnprocessableEntity,
ContentType = "application/http-problem+json",
Contents = (Stream stream) =>
{
problemDoc.Save(stream);
}
};
return resp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment