0

I get the '414 (Request-URI Too Long)' error when returning my image as a Base64 encoded string via the web api.

I currently have the following Action in my Web API Controller:

[System.Web.Http.Route("GetAllEvents")]
public async Task<IEnumerable<Event>> Get()
{
    var vm = EventsViewModel.NewInstance;
    return await vm.GetAllEvents();
}

And the vm.GetAllEvents() code:

public async Task<List<Event>> GetAllEvents()
    {
        var result = await DataStore.SelectAll();

        result.ForEach(x =>
        {
            var byteArray = File.ReadAllBytes(x.ThumbnailPath);
            x.ThumbnailEncoded = Convert.ToBase64String(byteArray);
        });

        return result;
    }

I consume the WebAPI action as follow:

this.ajaxRetrieve = function(url, data, onSuccessCallback, onErrorCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        async: false,
        dataType: 'JSON',
        success: function(result) {
            onSuccessCallback(result);
        },
        error: function(xhr, status, error) {
            onErrorCallback(xhr, status, error);
        }
    });
}

What would be the better approach to take, to avoid this from happening?

monstertjie_za
  • 7,277
  • 8
  • 42
  • 73

1 Answers1

1

i strongly suggest to you use stream instead of Base64String. its efficient and fast. here you can find the good example: Returning binary file from controller in ASP.NET Web API

UPDATE but you cant return array of streams with web api. so alternative option is byte array. something like this:

[HttpGet]
public async Task<List<byte[]>> Get()
{
    var files= await GetAllEvents();

    return files;
}

And the GetAllEvents() code:

public async Task<List<byte[]>> GetAllEvents()
{
    var list = new List<byte[]>();
    for (int i = 0; i < 5; i++)
    {
        var byteArray = await Task.Run(() => System.IO.File.ReadAllBytes(@"filePath"));
        list.Add(byteArray);
    }
    return list;
}

hope this could solve your problem.

Mohammad
  • 2,724
  • 6
  • 29
  • 55
  • With this example, should I create a separate Action in the controller for only returning the image?? – monstertjie_za Jun 08 '17 at 08:27
  • that's clear. return HttpResponseMessage instead of Task>. then just read the file as stream and return it just like the sample code. – Mohammad Jun 08 '17 at 08:29
  • These solutions don't work for me, I get the following: Failed to load resource: net::ERR_NAME_NOT_RESOLVED – monstertjie_za Jun 08 '17 at 12:40
  • my bad. after little googling i found out you cant have array of streams as your web api output. i updated my answer. hope this could solve your problem. – Mohammad Jun 08 '17 at 15:03