简体   繁体   中英

Return API result to view

I'm calling an API that returns a JSON string as below

{"ItemNumber":"5542","MD5Key":"md5key"}

What I want to do is to show these values in my View and this is what I have at the moment. The error is that my code is returning a View that not exists and my Model MD5 string is null, just the values that I fill directly are ok (ItemNumber, File).

Model

public class FileUpload
{
    [Required(ErrorMessage = "Item Number is required")]
    public int ItemNumber { get; set; }
    public byte[] File { get; set; }
    public string MD5Key { get; set; }
}

Controller:

[HttpPost]
public async Task<IActionResult> Upsert([FromForm] FileUpload obj)
{
    if (ModelState.IsValid)
    {
        var files = HttpContext.Request.Form.Files;
        if (files.Count > 0)
        {
            byte[] p1 = null;
            using (var fs1 = files[0].OpenReadStream())
            {
                using (var ms1 = new MemoryStream())
                {
                    fs1.CopyTo(ms1);
                    p1 = ms1.ToArray();
                }
            }
            obj.File = p1;
            obj.ItemNumber = 5542;
        }
    }

    await _cuRepo.CreateAsync("https://apiurl/method", obj.File, obj.ItemNumber);
    return View(obj);
    //This is returning a view Upsert, and obj.File, obj.ItemNumber are ok, just MD5 is null.
}

Repository (The main problem should be this)

public async Task<bool> CreateAsync(string url, byte[] file, int number)
{
    using (var client = new HttpClient())
    {
       client.DefaultRequestHeaders.Add("header", "aaaaaa");

        using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
        {
            content.Add(new StringContent(number.ToString()), "ItemNumber");
            content.Add(new StreamContent(new MemoryStream(file)), "File", "filename.txt");

            using (var message = await client.PostAsync(url, content))
            {
                var input = await message.Content.ReadAsStringAsync();
                //input has the JSON string

                if (input != null)
                    return true;
                else
                    return false;
            }
        }
    }
}

What can I do to return to my View after the post and populate my Model with the API call results?

i would create a new class for reponse object from from API. It is not a good idea to return user input to page. Better to have your own view model. (i use Json.NET nuget package for deserialization.

public class FileUploadResponse
{
    public int ItemNumber { get; set; }
    public string MD5Key { get; set; }
}

then deserisalize the response json to FileUploadResponse object

FileUploadResponse fileUploadResponse = JsonConvert.DeserializeObject<FileUploadResponse>(input); 

and return that instead of bool

return fileUploadResponse

you have to change the method signature too

public async Task<FileUploadResponse> CreateAsync(string url, byte[] file, int number)

then finally in your controller . you can

var response=await _cuRepo.CreateAsync("https://apiurl/method", obj.File, obj.ItemNumber);
return View(response);

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