简体   繁体   中英

Use of Reflection With object Class in C#

I have an API In Which I am receiving object of custom class

    [HttpPost("[action]")]
    public ResultSet AddApplication([FromBody] Application model)
    {
     // Code Here
    }

Application is a custom class and have around 64 properties .

Now Instead of Application object , I want to receive it as

    public ResultSet AddApplication([FromBody] object model)

Before Proceeding any further I want to check wether there are 64 key in "object model" or not

I can do that with Reflection on class

     Type T = typeof(LoanApplication);
     PropertyInfo[] P = T.GetProperties();

But how to check keys in an object Type ?

I want something like

[HttpPost("[action]")]
public ResultSet AddApplication([FromBody] object model)
{
 Type T = typeof(model);
 PropertyInfo[] P = T.GetProperties();
}

But here typeof(model) give error because its a variable , cant use it like a Type.

I need this in case if source send wrong data (less property or property name mismatched) than I should be able to find out what is wrong by comparing properties of My Custom Type and received object

So is there any way to get keys from object model in a list (with or without reflection)??

Update 1 :

[HttpPost("[action]")]
public ResultSet AddApplication([FromBody] Application model)
{
 // Code Here
}

If API receive wrong model than in above code model will be null (in debugging) and it means we will never know what went wrong, which property is mismatched or not present in received object

But

[HttpPost("[action]")]
public ResultSet AddApplication([FromBody] object model)
{
}

Here if model is wrong than still it will be received as object and by getting array or list of its property I can compare it with my custom type

That allow me to get every information of what went wrong , this response i want to send back so that user of this API so they will know what mistake they made

Ex : -

在此处输入图片说明

So as I mentioned in my comment, changing your good path to account for bad data is an extremely poor choice. Your good path should do it's job as if everything is normal. If you want to catch requests with invalid data then use an ActionFilter:

public LogInvalidDataRequstFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActinExecutingContext filterContext)
  {
    if (!filterContext.Controller.ViewData.ModelState.IsValid)
    {
      // Data isn't valid so now what?
    }
  }
}

[LogInvalidDataRequestFilter]
[HttpPost("[action]")]
public ResultSet AddApplication([FromBody] Application model)
{
 // Code Here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM