对于此操作,我们在asp.net core 2.0中编写了一个Web API,如果条件执行成功,我们将返回两种不同类型的响应,如果条件执行成功,它将返回zip文件作为对angular的响应,并将其保存在Machine中。
并且如果条件为false,它将发送JSON到Angular,因此在这里我们要向用户显示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());
}
}
答案 0 :(得分:0)
要接受两种类型的响应,我们需要按以下方式更改角度服务代码
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*
}
}