safriss
safriss

Reputation: 93

How to implement RazorViewEngine from WebAPIContrib?

We have the following scenario: ContactController : ApiController

Now the ContactController returns back Contact Model.

We would like for the controller to pass the result as a razor view by using the appropriate view from the web application.

I found this link

This is where Darrel Miller has a ViewEngineFormatter for api controllers. But I don't know how to specify which .cshtml view to use for the model returned. I have a breakpoint at WriteToStreamAsync method of the ViewEngineFormatter. It gets there and throws an error saying that it could not cast the object to be the View.

Here's where it throws an error:

    public override Task WriteToStreamAsync(Type type, object value, Stream stream, System.Net.Http.HttpContent content, TransportContext transportContext)
    {
        var view = (View)value;
        view.WriteToStream(stream, _viewEngine);
        var tcs = new TaskCompletionSource<Stream>();
        tcs.SetResult(stream);
        return tcs.Task;
    }

I'm just missing how to get an apicontroller to return back a razor view if specified datatype in the client request is 'html'.

Any help would be appreciated...

Upvotes: 1

Views: 349

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142154

You probably want to look at this https://github.com/WebApiContrib/WebApiContrib.Formatting.RazorViewEngine for a more up to date version. The original code I submitted has been updated plenty since then.

My original implementation required a stream of the .cshtml file to be passed into the View object along with the model. I think the newer stuff uses naming conventions for finding templates. I worked with this code in quite a while!

Upvotes: 1

Related Questions