1

I am writing a route function which looks something like this:

    public IHttpActionResult SomeRoute([FromBody] PostedData postedData)

The FromBody attribute will convert the data posted into the route to the type specified, with any properties which it can't cast in this way being set to null.

What I'm trying to do is check whether or not there are any null properties on the data which was posted (postedData in the example above). As I know the type, I can manually check each one, but I'd like to be able to implement such a check in a more generic way, and I'm wondering if this is possible.

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
  • 1
    that's maybe not a duplicate but certainly the right path to start. – kenny Apr 10 '19 at 12:56
  • 4
    Since it looks like you are using WebApi, the idiomatic way would be to decorate the properties of your `PostData` viewmodel with attributes like `[Required]`, and then you would be able to detect null (and other invalid data) through [ModelState](https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api) – StuartLC Apr 10 '19 at 13:00
  • 1
    I have to say, if this should be closed, it ought to be for being too broad, as it's certainly not a duplicate of the question it is flagged against. Given the question flagged as duplicate asks `How to iterate an objects properties`, my question might have been better asked as `I have an array of properties, how do I check whether any of them are null`, but that does not mean that this is a duplicate – OliverRadini Apr 10 '19 at 13:16
  • @StuartLC that sounds like a useful approach; I'll look into that, thanks – OliverRadini Apr 10 '19 at 13:17
  • 1
    @kenny I agree that this isn't a duplicate, but it appears that other members of the c# community disagree – OliverRadini Apr 10 '19 at 13:18

1 Answers1

1

You could use a combination of reflection and System.Linq.Expressions to generate a lambda that takes a PostedData and checks each property for null. It's a bit tricksy to get right, but will give you optimal performance over just using reflection to query the properties.

Sean
  • 60,939
  • 11
  • 97
  • 136