How to send byte array in c# ApiController
Asked Answered
G

1

5

Could someone please tell me how i can test this function :

[RoutePrefix("service")]
public class TestControler : ApiController
{
    [Route("function-route")]
    [HttpPost]
    public HttpResponseMessage Testfunction(TestData t_testData )
    {
        ...
        HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
        return httpResponseMessage;
    }
}

public class TestData
{
    public byte[] PreviewImage { get; set; }
    public byte[] FileAsByteArray { get; set; }
}

We have Swagger enabled via :

public void Configuration(IAppBuilder appBuilder)
{
    // Configure Web API for self-host. 
    HttpConfiguration config = new HttpConfiguration();

    //Using AttributeRoutes
    config.MapHttpAttributeRoutes();

    //Swagger
    config.EnableSwagger(c =>{
        c.SingleApiVersion("v1", "My Test API");
    }).EnableSwaggerUi();

    appBuilder.UseWebApi(config);
}

I really do not know how to test this API via swagger, or postman, or curl. The problem ist the byte[], how to send this? Does anyone how to test these kind of api?

Or, if there is another way to send any file (pdf, txt, docx, ...) combined with any picture (jpg, png, ...) without byte[], i would be glad to hear.

Gym answered 27/11, 2018 at 10:55 Comment(1)
You could try HttpPostedFileBase instead of byte[]Gradualism
B
13

I would base64 encode the byte arrays and change your model properties from byte[] to string. That should allow you to post these strings to your controller where you can convert them back to byte arrays.

To encode as base64 string use string byteString = Convert.ToBase64String(byteArray) and convert back using byte[] byteArray = Convert.FromBase64String(byteString).

Your updated code might look something like:

public class TestData
{
    public string PreviewImage { get; set; }
    public string FileAsByteArray { get; set; }
}

[Route("function-route")]
[HttpPost]
public HttpResponseMessage Testfunction(TestData t_testData)
{
    // convert base64 string to byte[]
    byte[] preview = Convert.FromBase64String(t_testData.PreviewImage);
    byte[] file = Convert.FromBase64String(t_testData.FileAsByteArray);
    ...
    HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
    return httpResponseMessage;
}

To test using postman you can use javascript functions atob() and btoa() to convert a byte array to a base 64 encoded string and vice versa.

Beanfeast answered 28/11, 2018 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.