.NET Core 3.1 convert to .NET 6 controller download method fails for no view - .net-6.0

I converted a .NET Core 3.1 project to .NET 6 and now the download method produces this error:
System.InvalidOperationException: The view 'ExcelDownload' was not found. The following locations were searched:...
This is the method:
public IActionResult ExcelDownload(string TIDList)
{
// ...
// ...
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content, contentType, fileName);
}
}
There has never been a view for this method and it worked with .NET Core 3.1. What's different with .NET 6 that causes this to look for a view?
Using the ClosedXML NuGet to create the Excel file.
Thanks!

Hi you can try FileContentResult
public async Task<FileContentResult> ExcelDownload(string TIDList)
{
var fileProvider = new FileExtensionContentTypeProvider();
if (!fileProvider.TryGetContentType($"{fileName.FileName}{fileName.Extension}", out string contentType))
{
contentType = fileName.Extension.RemoveDot();
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return new FileContentResult(content, contentType)
{
FileDownloadName = fileName
};
}
}

Related

authorization required when create pdf file

I am trying to generate pdf file using c# web api using the following code :
i have tried to change in the web.config but it didn't help.
[HttpGet]
public HttpResponseMessage Generate()
{
var stream = new MemoryStream();
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
I expected download pdf directly to my local disk but non worked.

How do we set content-type to "text/plain" in asp.net web api

We are using asp.net web api in our application, in that we are trying to return the response with content-type with text/plain format but We are unable to succeeded. Same thing we tried with ASP.NET MVC it is working fine could you please provide me equivalent solution in Web API.
Please find below for the function implemented in ASP.NET MVC
public JsonResult FileUpload(HttpPostedFileBase file)
{
string extension = System.IO.Path.GetExtension(file.FileName);
string bufferData = string.Empty;
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
var appendInfo = "data:image/" + extension + ";base64,";
bufferData = appendInfo + Convert.ToBase64String(array);
}
}
var result = new
{
Data = bufferData
};
return Json(result,"text/plain");
}
Could you please suggest same implementation in WebAPI.
Thanks,
Bhagat
Web Api does the JSON work for you, so you can simplify your code handling on the endpoint. By default, you need to make changes in your WebApiConfig.cs for everything to work nicely. I've modified your method below:
public HttpResponseMessage FileUpload(HttpPostedFileBase file) {
var result = new HttpResponseMessage(HttpStatusCode.NotFound);
var bufferData = string.Empty;
try
{
if (file != null)
{
var extension = System.IO.Path.GetExtension(file.FileName);
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
var array = ms.GetBuffer();
var appendInfo = "data:image/" + extension + ";base64,";
bufferData = appendInfo + Convert.ToBase64String(array);
result.StatusCode = HttpStatusCode.OK;
// Set Headers and Content here
result.Content = bufferData;
}
}
}
catch(IOException ex)
{
// Handle IO Exception
}
return result
}
The changes you need to make in your WebApiConfig.cs could look like this:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: null,
constraints: new { action = #"\D+" }
);
// This makes the response default into JSON instead of XML
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
As a note, the very fastest fix you can make to your code would be to do this, but I don't recommend returning strings.
public string FileUpload(HttpPostedFileBase file) {
var result = new HttpResponseMessage(HttpStatusCode.NotFound);
var bufferData = string.Empty;
if (file != null)
{
var extension = System.IO.Path.GetExtension(file.FileName);
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
var array = ms.GetBuffer();
var appendInfo = "data:image/" + extension + ";base64,";
bufferData = appendInfo + Convert.ToBase64String(array);
return bufferData;
}
}
// If you get here and have not returned,
// something went wrong and you should return an Empty
return String.Empty;
}
Good luck - there's lots of ways of handling files and file returns, so I want to assume you don't have some special return value on your handling.

How to use DotNetZip Library

I unziped the file I donwloaded. how and what library do i access in my asp.net mvc 3 app to be able to unzip a file that contains multiple files?
my controller code:
public ActionResult Upload(ScormUploadViewModel model)
{
if (ModelState.IsValid)
{
if (model.ScormPackageFile != null)
{
string zipCurFile = model.ScormPackageFile.FileName;
string fullPath = Path.GetDirectoryName(zipCurFile);
string directoryName = Path.GetFileNameWithoutExtension(zipCurFile);
Directory.CreateDirectory(Path.Combine(fullPath, directoryName));
using (FileStream zipFile = new FileStream(zipCurFile, FileMode.Open))
{
using (GZipStream zipStream = new GZipStream(zipFile, CompressionMode.Decompress))
{
StreamReader reader = new StreamReader(zipStream);
//next unzip the file? how to get the library i need?
}
}
thanks

How to Generate pdf of details view in mvc 3

I just want to generate a pdf document of the details presents in view on button click.
In order to generate a PDF file you will need some third party library as this functionality is not built-in the .NET framework. iTextSharp is a popular one.
So for example you could write a custom action result:
public class PdfResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = "test.pdf",
};
response.AddHeader("Content-Disposition", cd.ToString());
using (var doc = new Document())
using (var writer = PdfWriter.GetInstance(doc, response.OutputStream))
{
doc.Open();
doc.Add(new Phrase("Hello World"));
}
}
}
and then have your controller action return this result:
public class HomeController : Controller
{
public ActionResult Index()
{
return new PdfResult();
}
}

Convert PartialView Html to String for ITextSharp HtmlParser

I've got a partial view, i'm trying to use ITextSharp to convert the html to pdf. How can I convert the html to string so I can use ItextSharps HtmlParser?
I've tried something like this with no luck...any ideas?:
var contents = System.IO.File.ReadAllText(Url.Action("myPartial", "myController", new { id = 1 }, "http"));
I have created a special ViewResult class that you can return as the result of an Action.
You can see the code on bitbucket (look at the PdfFromHtmlResult class).
So what it basically does is:
Render the view through the Razor engine (or any other registered engine) to Html
Give the html to iTextSharp
return the pdf as the ViewResult (with correct mimetype, etc).
My ViewResult class looks like:
public class PdfFromHtmlResult : ViewResult {
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(this.ViewName)) {
this.ViewName = context.RouteData.GetRequiredString("action");
}
if (this.View == null) {
this.View = this.FindView(context).View;
}
// First get the html from the Html view
using (var writer = new StringWriter()) {
var vwContext = new ViewContext(context, this.View, this.ViewData, this.TempData, writer);
this.View.Render(vwContext, writer);
// Convert to pdf
var response = context.HttpContext.Response;
using (var pdfStream = new MemoryStream()) {
var pdfDoc = new Document();
var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();
using (var htmlRdr = new StringReader(writer.ToString())) {
var parsed = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(htmlRdr, null);
foreach (var parsedElement in parsed) {
pdfDoc.Add(parsedElement);
}
}
pdfDoc.Close();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", this.ViewName + ".pdf");
byte[] pdfBytes = pdfStream.ToArray();
response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
}
}
}
}
With the correct extension methods (see BitBucket), etc, the code in my controller is something like:
public ActionResult MyPdf(int id) {
var myModel = findDataWithID(id);
// this assumes there is a MyPdf.cshtml/MyPdf.aspx as the view
return this.PdfFromHtml(myModel);
}
Note: Your method does not work, because you will retrieve the Html on the server, thereby you loose all cookies (=session information) that are stored on the client.

Resources