Wasyster Wasyster - 2 months ago 8
C# Question

RuntimeBinderException: Operator '==' cannot be applied to operands of type 'GiftUWish.Model.ViewModels.GiftPicture' and 'System.Type'

I have an web API that stores pictures in DB. We store the pictures web address link or in base64 format. Now when we returns the image, and the image is linked in for example in facebbok post, we got the error:

RuntimeBinderException: Operator '==' cannot be applied to operands of type 'GiftUWish.Model.ViewModels.GiftPicture' and 'System.Type'

Here is my code

[HttpGet]
[Route("{giftId}/picture")]
[AllowAnonymous]
public IActionResult GetCustomGiftImage(int giftId)
{
ResponseMessage<dynamic> response = _giftService.GetCustomGiftImage(giftId);

if (response.StatusCode && response.ResultObject != null && response.ResultObject == typeof(GiftPicture))
{
FileContentResult file = new FileContentResult(response.ResultObject.Content, response.ResultObject.MimeType);

return file;
}
else if(response.ResultObject == typeof(string))
{
return string.IsNullOrEmpty(response.ResultObject) ? string.Empty : response.ResultObject;
}

return BadRequest();
}

public ResponseMessage<dynamic> GetCustomGiftImage(int giftId)
{
ResponseMessage<dynamic> response = new ResponseMessage<dynamic>();

try
{
GiftEntity gift = _repository.FindByID(giftId);

if (!string.IsNullOrEmpty(gift.Image) && gift.Image.StartsWith("data:"))
{
GiftPicture giftPicture = CreateGiftPicture(gift.Image);
response.ResultObject = giftPicture;
}
if (!string.IsNullOrEmpty(gift.Image) && gift.Image.StartsWith("http"))
{
response.StatusCode = true;
response.ResultObject = gift.Image;
}

return response;
}
catch (Exception ex)
{
response.StatusCode = false;
response.ErrorMessage = SetErrorMessage(ex);
response.ResultObject = new GiftPicture();

return response;
}
}

private GiftPicture CreateGiftPicture(string dataUri)
{
string[] dataUriMetaAndContent = dataUri.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string dataUriMeta = dataUriMetaAndContent[0];
string dataUriContent = dataUriMetaAndContent[1];

string mimeType = dataUriMeta.Replace("data:", "").Split(';')[0];

return new GiftPicture(mimeType, dataUriContent.Base64DecodeToBytes());
}

Answer

I think the error is here:

response.ResultObject == typeof(GiftPicture))

You are trying to compare a GiftPicture instance to a type - if you want to check to see if ResultObject is an instance of GiftPicture then try the following:

response.ResultObject is GiftPicture

(You should also do the same where you check against typeof(string))

Comments