我正在嘗試使用此下載此 PDF 檔案AJAX Post并回傳 templateFile 模型。我收到錯誤無法將 TemplateFileDto 型別轉換為 IhttpActionResult。我應該回傳不同的東西嗎?任何幫助都會很棒。
printItems(versionKeys: string[]): JQueryPromise<any> {
console.log('printItems');
$.ajax({
type: "post",
contentType: "application/json",
data: JSON.stringify(versionKeys),
url: this.apiUrls.PrintTemplates,
success: function (data, status, xhr) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
console.log('success');
}
});
return;
}
控制器
[HttpGet, HttpPost]
[ApplicationApiAuthorize("Administrator, ContentManager")]
public IHttpActionResult PrintTemplates([FromBody] List<string> versionKeys)
{
var templates = versionKeys
.Select(v => TemplatesDataService.GetTemplate(v))
.ToList();
var templateIds = templates.Select(b => b.Id).ToList();
var templateFile = TemplatesDataService.PrintTemplate(templateIds);
return templateFile;
}
模型
public class TemplateFileDto
{
public long? Id { get; set; }
public byte[] Content { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
}
uj5u.com熱心網友回復:
您的PrintTemplates方法的回傳型別是IHttpActionResult;但是,您的templateFile變數的型別是TemplateFileDto.
由于TemplateFileDtoand之間沒有關系IHttpActionResult(例如,TemplateFileDto不實作IHttpActionResult介面),編譯器無法將此變數隱式轉換為適當的型別 - 因此出現錯誤。
您可以在此處找到有關此錯誤的更多詳細資訊。
解決此問題的最簡單方法是呼叫Ok方法,并將其templateFile作為引數。這將確保您回傳的內容格式正確,并且 HTTP 回應代碼設定為 200。
它應該像改變你的PrintTemplates方法一樣簡單:
return templateFile;
對此:
return Ok(templateFile);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340350.html
標籤:C# asp.net-mvc 打字稿
