I created a method in my Controller that returns a doc file from a html string.
public class MyController : Controller {
private FileContentResult Html2DocxResult(string html, string fileDownloadName) {
byte[] docBytes = DocumentExport.Html2Docx(html);
FileContentResult result;
using (var ms = new MemoryStream(docBytes)) {
result = this.File(ms.ToArray(), "application/msword", fileDownloadName + ".docx");
}
return result;
}
}
When I need to send a file to a client, I can use like that:
public class MyController : Controller {
[HttpPost]
public FileContentResult GenerateDocument(string fileName) {
string html = "<h1>Title</h1><p>Content goes here!</p>";
return Html2DocxResult(html, fileName);
}
}
The problem is that I'd like to call Html2DocxResult
in any Controller I want to. I think make the method public isn't a good practice because, in this way, I would be creating an accessible Action that I don't want to exist. For exemple, an user could call http://mywebsite.com/MyController/Html2DocxResult?hml=<p>test</p>&fileDownloadName=MyTest
and I don't want this.
I tried to create a class to have Html2DocxResult
like an static method to serve all Controllers. Like that:
namespace BancoQuestoesMVC.Utils {
public class DocumentExport {
public static FileContentResult Html2DocxResult(string html, string fileDownloadName) {
byte[] docBytes = DocumentExport.Html2Docx(html);
FileContentResult result;
using (var ms = new MemoryStream(docBytes)) {
result = Controller.File(ms.ToArray(), "application/msword", fileDownloadName + ".docx");
}
return result;
}
}
}
But the method Controller.File
can't be accessible in this context.
I could pass the current Controller like a parameter to Html2DocxResult
and call callerController.File
and the problem would be solved. But it doesn't seem a good practice for me.
Someone know how to solve this kind of problem? Is there an design pattern appropriate for that? How a non-controller class can have methods that return ActionResult but without call for a Controller. Is that idea a problem of concept?