简体   繁体   中英

Comparing two object in WebApi HttpPost request doesn't work

I post an ProductBO object to a HttpPost service but when compare it return false.

I add debugger and evaluate(QuickWatch) value's at run time all other member of both classes are equal but when i compare product.Equals(testProduct) it retuns false. I am passing data as..

I am passing data using Postman in raw

{
    "Id" :1, 
    "Name" : "Tomato Soup", 
    "Category" :"Groceries", 
    "Price" : 1
}

and text type is application/json . What am i doing wrong.and whether It is a better approach to pass an object like this or not.

     public IHttpActionResult GetTestProduct(ProductBO testProduct) {
        ProductBO product = new ProductBO { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 };
        if (product.Equals(testProduct)) //also tried for product == testProduct both return false
        {

            return Ok(product);
        }


        if (product.Id == testProduct.Id) 
        { 

        }
        if (product.Name.Equals(testProduct.Name))
        {
        }

        return Ok("working");
    }

For reference types, the Equals method compares object references and it returns false because testProduct and product are pointing to 2 different addresses in memory. You could implement the IEquatable<T> interface on your view model to indicate how to perform the comparison:

public class ProductBO : IEquatable<ProductBO>
{
    public int Id { get; set; }

    public string Name { get; set; }

    public bool Equals(ProductBO other)
    {
        return this.Id == other.Id && this.Name == other.Name;
    }
}

As the docs says

If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object.

In your case you want to compare the content of the objects and not thier reference. The simple solution to achieve this is to serialize both objects as json and compare the strings

JsonConvert.SerializeObject(product) == JsonConvert.SerializeObject(testProduct)

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