1

Hello Please Help me This is my controller,It's can catch if i send image on postman without ApiRequest. But i can't catch images on my React Application. Also i cant get arrays fields. In this ProductCreateRequest model has a List fields. I send axios this fields with array but .net core cant catch. I loose my mind please help me i dont understand why

This is my Controller code

[HttpPost]
        [Consumes("application/json", "multipart/form-data")]
        public ApiResponse<bool> CreateProduct([FromForm] ApiRequest<ProductCreateRequest> request)
        {
            //this.ValidateRequest(request, null);
            var productRequest = request.data;
            var response = _productService.CreateProduct(productRequest);
            string message = String.Empty;
            if (productRequest.ProductImages !=null)
            {
                foreach (var image in productRequest.ProductImages)
                {

                    var addedImage = this.UploadFileAsync(image, "image/jpeg");

                    if (addedImage.Result.Status == ImageUploadState.Success)
                    {
                        var responseImage = _imageService.CreateImage(addedImage.Result, response.Id, "ProductId");
                        if (!responseImage)
                            message = "An error was on upload Image ! Please try again but you should first look which image cant upload !";
                    }
                    if (addedImage.Result.Status == ImageUploadState.NotExist)
                    {
                        message = addedImage.Result.ErrorMessage;
                    }
                    if (addedImage.Result.Status == ImageUploadState.Error)
                    {
                        message = addedImage.Result.ErrorMessage;
                    }
                }
            }
            if (productRequest.ProductType == ProductType.Accessory && productRequest.ParentProductId == null)
            {
                message = message == String.Empty ? "Accessory added but it is not assigned to any product." : message + "***and***" + "Accessory added but it is not assigned to any product.";
            }
            return this.Response(true,message, null);
        }

This is my ApiRequest Class

[DataContract(Name ="api-request"),Serializable]
    public class ApiRequest<T>
    {
        public ApiRequest(T data,byte[] token)
        {
            this.data = data;
            this.token = token;
        }
        public T data { get; set; }
        public byte[] token { get; set; }
        public string Language { get; set; }

    }

This is my Product Request Model

    [DataContract(Name ="product-create-request"),Serializable]
    public class ProductCreateRequest
    {
        public double UnitPrice { get; set; }
        public int UnitStock { get; set; }
        public string Description { get; set; }

        [FromForm(Name ="productImages")]
        public IEnumerable<IFormFile> ProductImages { get; set; }
        public List<TechnicalInfo> TechnicalInfos { get; set; }
        public int MainCategoryId { get; set; }
        public int CategoryId { get; set; }
        public int? ParentProductId { get; set; }

        public List<Product> SubProduct { get; set; }
        public ProductType ProductType { get; set; }

    }

This is my React App code

    const data = new FormData();
        data.append('data',JSON.stringify(product));
        const url = `${process.env.REACT_APP_API_URL}/product/createproduct`;
        const config = {
            headers: { 'content-type': 'multipart/form-data' },
        };
        const values = {
            data,
            language: 'tr-TR',
        };
        await axios.post(url, data, config);

Please help me i dont understand why i cant catch arrays values.

1 Answer 1

1

i can't catch images on my React Application. Also i cant get arrays fields.

To achieve your requirement of posting data with file(s) and make the data can be bound to action parameter well, you need to do following modifications:

1)A parameterless constructor for class ApiRequest

[DataContract(Name = "api-request"), Serializable]
public class ApiRequest<T>
{
    public ApiRequest()
    {

    }
    public ApiRequest(T data, byte[] token)
    {
        //...

Note: this doc shows deserialization behavior within System.Text.Json

2)Dynamically generate and populate formdata like below

const data = new FormData();
//...
data.append('language', language_here);

//...
data.append('data.unitStock', unitStock_here);
data.append('data.productImages', productImage1_here);
data.append('data.productImages', productImage2_here);
//...

Note: this doc explains what model binding is and how it works

3)To bind byte[] data, you may need to use the ByteArrayModelBinder

Test Result

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much for your answer , you save my mind :D
Hi @aaliakinci, if the solution did help achieve the requirement, kindly accept it - see What should I do when someone answers my question?
Sorry i forgetted

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.