RuntimeBinderException:运算符' =='不能应用于类型' GiftUWish.Model.ViewModels.GiftPicture'的操作数。和' System.Type'

时间:2016-09-09 20:24:36

标签: c# asp.net-mvc dynamic

我有一个用于在DB中存储图片的Web API。我们存储图片网址链接或base64格式。现在,当我们返回图像,并且图像链接在例如facebbok帖子中时,我们得到了错误:

RuntimeBinderException:Operator' =='不能应用于类型' GiftUWish.Model.ViewModels.GiftPicture'的操作数。和' System.Type'

这是我的代码

[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());
}

1 个答案:

答案 0 :(得分:2)

我认为错误就在这里:

response.ResultObject == typeof(GiftPicture))

您正在尝试将GiftPicture实例与类型进行比较 - 如果您想检查ResultObject 是否是 GiftPicture的实例,请尝试以下操作:

response.ResultObject is GiftPicture

(您也应该对typeof(string)

进行检查