ControllerContext Null

2

I have the following code:

PDFController Ctrl = new PDFController();
            byte[] ArquivoPDF = Ctrl.GerarPDF(xml); 

This part above is in WebApi, where I create a new instance of the Controller to use the function that is in it. The code below is already the part of the controller:

public class PDFController : Controller
{
 public string RenderizaHtmlComoString(string NomeView, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, NomeView);

            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);

            return sw.GetStringBuilder().ToString();
        }
    }
}

In the part that will form the viewResult variable, it gives an error and says that the ControllerContext can not be null. can anybody help me? * This Controller is not bound to any View.

    
asked by anonymous 10.03.2017 / 18:21

1 answer

2

Your ControllerContext in this case will always be null because you are instantiating the controller "manually".

Generally the controller is created by an IControllerFactoy which is usually the DafaultControllerFactory, it creates the controller with all the necessary dependencies that the ControllerContext includes.

Normally when you need common methods between controllers, you create a base controller that is inherited from the other controllers. In your case it would look something like this:

    public class BaseController : Controller
{
    // GET: Base
    public byte[] GerarPDF(string content)
    {
        //Código que gera o pdf.

        return new byte[] { };
    }
}
    public class ControllerA : BaseController
{
    public byte[] AlgumMetodo()
    {
        return GerarPDF("");
    }
}

public class ControllerB : BaseController
{
    public string AlgumOutroMetodo()
    {
        byte[] pdf = GerarPDF("");

        return "";
    }
}
    
10.03.2017 / 20:11