首页 > 解决方案 > 如何从asp.net核心Web API方法以角度获取不同类型的responseType

问题描述

对于此操作,我们在 asp.net core 2.0 中编写了一个 Web API,如果条件成功执行,我们将返回两种不同类型的响应,它将返回 zip 文件作为对角度的响应,我们将保存在 Machine。

如果条件为假,它会将 JSON 发送到角度,所以在这里我们希望向用户显示 PopUp 以及 JSON 数据

但是我们将 [responseType: "arraybuffer"] 保留在角度应用程序中,因此对于这两种情况,我们都会得到 "arraybuffer" 作为响应

//asp.net core web api code
// code wrote for two different return type 

if(condition == true )
{
  return File(zipBytes, "application/zip", "Data.zip");
}
else
{
  return Json(new Response { Code=111,Data= 
                            JsonConvert.SerializeObject(myList)});
}

//************************************************ ********************//

//Angular 6 Code
//Code wrote for getting a response as a zip in the angular service file 

postWithZip(path: string, body: Object = {}): Observable<ArrayBuffer> {
    return this.http
      .post(`${path}`, JSON.stringify(body), {
        headers: this.setHeaders({ multipartFormData: false, zipOption: true }),
        responseType: "arraybuffer"
      })
      .catch(this.formatErrors);
  }

正如您在上面的角度代码中看到的那样,它处理 zip 文件响应,但不适用于 JSON 响应。

那么在这种情况下我们如何实现这两种场景呢?

//************************************************ *************//

// this is the Method we wrote in asp.net 
[Route("GetAcccountWithCredits")]
        [HttpPost]
        public IActionResult GetAccountWithCredtis([FromBody]AccountsWithCreditsRequest tempRequest)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                BusinessHelper businessHelper = new BusinessHelper(_hostingEnvironment, _iconfiguration, _smtpDetails, _options, _dbSettings);
                //Get data from stored procedure
                var accountsWithCredits = businessHelper.getAccountsWithCredtis(tempRequest);

                //Delete existing files from Excel folder
                string[] filePaths = Directory.GetFiles(_hostingEnvironment.ContentRootPath + "\\Excels\\Accounts with Credit Balances");
                foreach (string filePath in filePaths)
                {
                    System.IO.File.Delete(filePath);
                }

                DataTable dt = new DataTable();
                //Convert stored procedure response to excel
                dt = businessHelper.ConvertToCSV("Garages", accountsWithCredits, _hostingEnvironment.ContentRootPath + "\\" + _iconfiguration["CSVFilePath"]);
                List<string> myList = new List<string>();
                if (dt.TableName == "codeDoesNotExits")
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        myList.Add((string)row[0]);
                    }
                }
                if (myList.Count == 0)
                {
                    //Create List of excel files details(name, path)
                    List<FileObjectDeails> listOfFiles = new List<FileObjectDeails>();
                    FileObjectDeails garadesList = new FileObjectDeails();
                    garadesList.FileName = _iconfiguration["GaragesFileName"];
                    garadesList.FilePath = _hostingEnvironment.ContentRootPath + "\\" + _iconfiguration["CSVFilePath"] + "\\" + _iconfiguration["GaragesFileName"];
                    listOfFiles.Add(garadesList);


                    if (tempRequest.EmailId != "")
                    {
                        string subject = _iconfiguration["AccountsWithCreditEmailSubject"];
                        string body = _iconfiguration["AccountsWithCreditEmailBody"];
                        //Send Email with files as attachment
                        businessHelper.SendEmail(listOfFiles, tempRequest.EmailId, subject, body);
                    }

                    //Convert files into zip format and return
                    byte[] zipBytes;
                    using (var ms = new MemoryStream())
                    {
                        using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                        {
                            foreach (var attachment in listOfFiles)
                            {
                                var entry = zipArchive.CreateEntry(attachment.FileName);

                                using (var fileStream = new FileStream(attachment.FilePath, FileMode.Open))
                                using (var entryStream = entry.Open())
                                {
                                    fileStream.CopyTo(entryStream);
                                }
                            }
                        }
                        ms.Position = 0;
                        zipBytes = ms.ToArray();
                    }
                    return File(zipBytes, "application/zip", "GarageData.zip");
                }
                else
                {
                    return Json(new Response { Code = 111, Status = "Got Json", Message = "Fount Account Code which is not present in XML File", Data = JsonConvert.SerializeObject(myList) });
                }
            }
            catch (Exception e)
            {
                return BadRequest(e.Message.ToString());
            }
        }

标签: angularasp.net-web-apiasp.net-coreangular6

解决方案


为了接受这两种类型的响应,我们需要更改角度服务代码,如下所示

 postWithZip(
    path: string,
    body: Object = {}
  ): Observable<HttpResponse<ArrayBuffer>> {
    return this.http
      .post(`${path}`, JSON.stringify(body), {
        headers: this.setHeaders({ multipartFormData: false, zipOption: true }),
        observe: "response",
        responseType: "arraybuffer"
      })
      .catch(this.formatErrors);
  }

然后我们可以使用 contentType 来识别两个响应,如下所示

   res => {
        if (res.headers.get("content-type") == "application/zip") {
          *//Write operation you want to do with the zip file*
        } else {
          var decodedString = String.fromCharCode.apply(
            null,
            new Uint8Array(res.body)
          );
          var obj = JSON.parse(decodedString);
         *//Write operation you want to done with JSON*
        }
      }

推荐阅读