Last active
March 2, 2016 08:37
-
-
Save jchannon/dd8086aaa51ac50a4dcc to your computer and use it in GitHub Desktop.
Nancy + problem+json extension using https://www.nuget.org/packages/Tavis.Problem/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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" | |
] | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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