Short story about what I am doing and why. I had been doing view to string conversion in Mvc project, but suddenly all project moved to the REST API. But I had to use razor engine to convert my view with all model data there, so I was trying to use directly from api, but it didn't work for me, so I decided to create a Mvc controller and call it directly from API, what is missing, only ControllerContext, because when I create controller directly, it appears to be null.

Here is my Api controller

public class AttachmentController : ApiController
{
    [HttpGet]
    public async Task<IHttpActionResult> Get(long id)
    {
        try
        {
            var mvcController = new AttachmentMvcController();

            var result = await mvcController.Get();

            return Ok(result);
        }
        catch (Exception e)
        {
            return InternalServerError(e);
        }
    }
}

and this is my Mvc Controller

public class AttachmentMvcController : Controller
{
    public AttachmentMvcController(){ }

    public async Task<byte[]> Get()
    {
        string result;

       // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // HERE IS MY PROBLEM, I NEED this.ControllerContext, but it is null !!!
        if (ControllerContext == null)
        {
            // create it and do task 
            var factory = DependencyResolver.Current.GetService<IControllerFactory>() ?? new DefaultControllerFactory();
            AttachmentMvcController controller = factory.CreateController(ctx.RequestContext, "AttachmentMvc") as AttachmentMvcController;

            RouteData route = new RouteData();
            route.Values.Add("action", "ActionThatUsesControllerContext"); // ActionName, but it not required

            ControllerContext newContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), route, controller);
            controller.ControllerContext = newContext;
            result = await controller.ActionThatUsesControllerContext(id);
        }
        else
        {
            result = await this.ActionThatUsesControllerContext(id);
        }

        return result;
    }

    private async Task<byte[]> ActionThatUsesControllerContext()
    {
        {....}
        // here I am trying to use helper that uses that controller context
        string viewAsString = ControllerContext.RenderPartialToString("MyView", requestModel);
        {....}
    }
}

If anyone has idea how to get that ControllerContext or any other ways to get my razor engine render view inside ApiController, please share.

Related posts

Recent Viewed