I have the following action in my ASP.NET Web API:
public IEnumerable<Car> carssOfUser(int id, String username, String password)
{
using (var context = new CarEntities())
{
// Authorization. Allow user only to get his own cars
User userQueried = context.Users.Where(u => u.id == id).FirstOrDefault();
if (!userQueried.username.Equals(username))
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
//return null;
}
IEnumerable<Car> cars = context.Cars.Where(p => p.ownerId == id).ToList();
return cars;
}
}
However, if I query it from Android application to obtain cars of given users (through json).. let’s say with id 2, it returns collection of 9 cars (that’s correct, user 2 has 9 cars), but only first car has proper field values (name, price etc.), the rest of cars have null in all fields.
That’s really strange, cause the problem happened when I added these lines of code:
// Authorization. Allow user only to get his own cars
User userQueried = context.Users.Where(u => u.id == id).FirstOrDefault();
if (!userQueried.username.Equals(username))
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
//return null;
}
After removing it, everything works perfectly fines and all cars have proper values in fields (not nulls anymore)…
Do you have any idea how to explain this imo very strange behavior?
I don’t think it matters (cause all other actions where I don’t have this kind of authorization works without problems), but I want to mention that from Android app I use gson to deserialize, and on server side I use JSON.NET to serialize.
I looked at the database access code and I put authorization code into using statement:
It helped and it works now.
However, I’m not really sure why executing this code within separate context helped..
any ideas?