I am trying to download this PDF file using this AJAX Post
and returning the templateFile Model. I am getting the error cannot convert type TemplateFileDto to IhttpActionResult. Should I Return something different? Any help would be great.
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;
}
Controller
[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;
}
Model
public class TemplateFileDto
{
public long? Id { get; set; }
public byte[] Content { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
}
CodePudding user response:
The return type for your PrintTemplates
method is IHttpActionResult
; however, the type of your templateFile
variable is TemplateFileDto
.
Since there's no relationship between TemplateFileDto
and IHttpActionResult
(e.g., TemplateFileDto
doesn't implement the IHttpActionResult
interface), the compiler cannot implicitly convert this variable to the appropriate type - hence the error.
You can find more detailed information on this error here.
The easiest way to resolve this is by calling the Ok
method, with templateFile
as a parameter. This will take care of making sure the content you return is formatted correctly and the HTTP response code is set to 200.
It should be as simple as changing your PrintTemplates
method from this:
return templateFile;
To this:
return Ok(templateFile);