简体   繁体   中英

MVC Jsonresult from memorystream json file

Thanks in advance,

I need an MVC controller (=GetFreqSuggestions) that returns a JsonResult to feed the prefetch of a Typeahead javascript function.

$(function() {
    var bestPictures = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch:{
            url: '../Reports/GetFreqSuggestions',
            ttl:0
        },
        remote: '../Reports/ToDo?q=%QUERY'
 });

 bestPictures.initialize();

 $('#remote .typeahead').typeahead({
         hint: true,
         highlight: true,
     },
     {
         name: 'best-pictures',
         displayKey: 'value',
         source: bestPictures.ttAdapter()
     });
});

The Json file is obtained from a azure blob storage as memorystream :

public async Task<bool> DownloadStreamFromBlobAsync(MemoryStream memStr, string blobContainerName, string blobName, ILogger log)
{
    Stopwatch timespan = Stopwatch.StartNew();
    try
    {
        CloudBlobContainer container = GetCloudBlob(blobContainerName);
        if (container != null & memStr!=null)
        {                   
             CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
             await blockBlob.DownloadToStreamAsync(memStr);
        }
    }
    catch (Exception e)
    {
        log.Error(.....);
        return false;
    }
    timespan.Stop();
    log.TraceApi(.......);
    return true;
}

In the controller I would like to convert the memorystream containing a pervious uploaded json file to a jsonresult.

 public async Task<JsonResult> GetFreqSuggestions()
 {
     MemoryStream mem = await _suggestoinProvider.DownloadFrequentSuggestionsAsync();
     if(mem != null)
     {
         return ????
     }
     return null;
 }

All suggestions are welcome. (I have tested with return Json(data, JsonRequestBehavior.AllowGet); that works perfectly when data was not a stream) I do not prefer to save a Json file first on a server.

I think that either .ToArray() or .ReadToEnd() will do the trick here:

return Json(mem.ToArray(), JsonRequestBehavior.AllowGet);

or

return Json(mem.ReadToEnd(), JsonRequestBehavior.AllowGet);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM