4

It's a quite odd task to do, but I can't change the requirements. We have to write a WCF service (SOAP, not REST) and return an HTML as a property on response object.

I don't want to use:

  • hard-coded strings and use string.Format() to fill in some values;
  • t4 template as not many people can support this approach in the future;
  • WebForm controls as most of our developers are used to work with MVC projects.

I already know how to render some ActionResult to a string. So, ideally, I would like to be be able to create a controller, invoke some action and get an ActionResult.

For that, I created MVC application and added service.svc file to it. Service work fine - I can invoke its methods and receive results. But my problems start when I try to render Razor View. If I simply create an instance of any controller and then invoke an action, controller's property ControllerContext is null and hence View can't be rendered. I tried crafting ControllerContext on the fly, but seems like I'm missing something.

I found very similar question here, but the solution offered there didn't work for me as HttpContext.Current is null inside of wcf methods.

Does any body know how to achieve that? Or maybe somebody can sugggest other simple and flexible way to render HTML inside of WCF method?

Community
  • 1
  • 1
davidoff
  • 2,175
  • 3
  • 16
  • 23

2 Answers2

2

You should also have a look at the Nancy framework (http://nancyfx.org), as their implementation of the RazorEngine is more lightweight.

I've had a fair amount of success using Nancy to generate HTML on demand - because it was designed as being inherently testable, you can abuse it to your own ends as a templating framework pretty easily.

Rammesses
  • 410
  • 5
  • 12
1

You will need to host the Razor Engine in your app. Look at this article Rendering ASP.NET MVC Views to String, especially the section "Rendering without a ControllerContext"

Also, much more info can be found in this answer Render a view as a string. (The are several "correct" answers, with different contexts)

Community
  • 1
  • 1
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206