[英]Sending class objet to asp.net core web api http get method from angular 12
[英]How to get different types of responseType in angular from asp.net core web API method
對於此操作,我們在asp.net core 2.0中編寫了一個Web API,如果條件執行成功,我們將返回兩種不同類型的響應,它將返回zip文件作為對angular的響應,我們將保存在Machine。
如果條件為false,它會將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());
}
}
為了接受這兩種類型的響應,我們需要在角度服務代碼中進行如下更改
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*
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.