Simple ModelState Extension

Something might be out there like this already but I recently found myself needing to not only validate a model that has been posted or put into an API but also be able to easily roll up those validation errors and ship them back.  I know there are lots of ways to accomplish this but here was my approach.

First, start with the model and a validation

Super simple I know but we’ve got a basic DTO that has a requirement to always carry the Name property.

And we can have a controller that takes this model and validates it.

This is great.  We can do something interesting when we receive bad input.

But my requirement was to have my API return a list of all of the errors that came off the Model.  So my approach was to extend the ModelState class.  What this gave me the opportunity to do is iterate the errors, put them into a container and the return that as part of the status 400 response to the client so that they can do something interesting with the output.

So here is the extension method

Very straightforward.  What I’m doing here is looking at the ModelStateDictionary, looping the values and looking for errors.  If errors exist for  a specific value then I add the string error message onto a List<string> and then at the end return a container object that holds the errors.  If I wanted, I could put more on the ValidationResponse class but this is just an example so I believe you could further extend the concept.

The response class looks like this

Now your controller action looks like this.

You’ll have a response which is a 400 with an array of errors.

And your finished.  Hope this helps as you think about validating API input


Processing text/plain in ASP.NET Web API

Seems straightforward right?  And it is.  The only missing piece is that your API doesn’t know what to do when a form body comes across as “Content-Type”: “text/plain”

Have no fear, dotnet core has a class named InputTextFormatter that is a base class for TextInputFormatter which has derived classes for working with JSON and XML.  So the below snippets will get you a basic implementation for dealing with plain text and how to add it to your MVC pipeline

And to make sure that this code is injected in your MVC pipeline.  In your Startup.cs or wherever you register your dependencies

And then inside of your controller

And that’s it.  You’ve successfully handled text/plain in your controller and can be reused in any other controller action that needs to have text/plain as the content type.


AWS SNS HTTP POST to C# (dotnet core 2.1)

I spent way too much time on this today and I wanted to document what I found and a simple work around for what seems to be an oversight on AWS’ part.  (read some forums and you’ll see the threads)

When setting up an SNS Topic for instance when you have two services (APIs) that you want to connect together, you need to first confirm that the subscriber to can handle the messages. The part that took me forever to get (it is documented as such) but when looking at JSON messages all day, you don’t pay attention to the header.

Here is the link to the setup article

Section 1.  Notice that there is a sample payload for what you might expect.  The tip for you is to pay attention to the Content-Type in the header.  Although that body in the POST is JSON, they are sending it as text/plain.

And when using C#, having JSON as a parameter in [FromBody] is a no brainer with the serialization into your object happening automatically. However, with text/plain, C# doesn’t know what to do with the input.  The below method is just an approach to dealing with this.  I’m going to wrap this up at some point soon and create a custom InputFormatter which I’ll post once I get that done.  For now, the below code will get you going.  Best of luck and I hope this saves you some time!


Error Handling with Node.js and Express

Probably a topic that has been written on quite a bit but as with some blog posts, doing it one more time is hopefully another piece of community documentation as well as potentially helpful to someone struggling with a task.

Express is probably the web framework that most people hear/learn about first and with my limited Node experience the first one I came across.  The following paragraphs won’t be about competitors to it or really more beyond what the title describes, but if you are interested, check out (there are several others)

This week while looking at a bug in our platform, I realized quickly that the application was not the problem, yet the underlying API which is written in Node and utilizing Express.  I kept seeing in the logs “Can’t set headers after they are sent to the client”.  When looking at the route, the first thing I noticed was that when an error was occurring the code was just using 500 as a catch all and then calling

Beyond the generic exception, in the app.js there was an attempt at an error handler setup which was also sending headers back to the requestor.  So to clean this code up and put a better status on response I changed to this

So I cleaned up the code inside of the route which both returns a response correctly and doesn’t double send headers as that res.status(200).json({}) won’t be called unless there truly are no errors in the processing that the API is doing. Now popping on over to app.js which handles app setup and route configuration, I added the following at the bottom of the file.  Important Note: Adding a wildcard route must be at the bottom as it is essentially a “fallout” and it’ll match anything.

Few things about the above.

  1. Note that before anything I have that wildcard route and I’m treating those requests as Not Found and returning 404 as the HTTP status.
  2. Development based route for error handling.  In the payload in the response, I’m setting error: err which will show the actual descriptive error that I probably care about only when in development. Notice no next() as I want to end the pipeline right there
  3. The production handler that only returns the HTTP status and the error message I want.  Such as “Invalid Request”, “Bad Request, check your parameters” or whatever I want to return to the caller.

Like I mentioned in my last post, I’ll be sharing things I’ve learned, am learning or just general fodder along the way.  I hope this is helpful to someone and if not applicable to what you are working on, perhaps just something new that you can file away!