Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API - Rendering Razor view by default?

How do I get Web API to render a Razor view using the model that it returns? And only XML/JSON when the accept headers (or .extension) is set? Is this even possible?

It seems crazy to require one set of controllers for rendering HTML and another for JSON/XML if they're working on the same models.

Update Darrel Miller has already written a ViewEngineFormatter for Razor which might do the trick, though haven't tried it yet.

like image 307
James Crowley Avatar asked May 16 '12 09:05

James Crowley


People also ask

How do I return the render razor view from Web API controller?

ASP.NET MVC4 Web API controller should return Razor view as html in json result property. Message=The method or operation is not implemented. var viewResult = ViewEngines.

Does Web API have view?

Views are optional in an MVC project. They are only used for projects where there are HTML pages involved. You can use MVC to build web services and they don't require Views.

What is a razor view page?

Razor Pages is a newer, simplified web application programming model. It removes much of the ceremony of ASP.NET MVC by adopting a file-based routing approach. Each Razor Pages file found under the Pages directory equates to an endpoint.


1 Answers

I asked a similar question about this in the past on StackOverflow, because I wanted to do the same thing. However, I eventually ended up with an "Api" area and set of controllers, and a standard set of MVC controllers for the website.

In hindsight this actually wasn't a bad thing. I've found I tend to do different things in each set of controllers anyway. My views aren't just CRUD but tend to contain extra contextual data, so returning view models specific to that page is nice.

I think if I had stuck to my goal of combining the two I might have ended up with either over-complicated controllers or a user experience that wasn't as optimal as it could have been. So while this isn't a direct answer to your question, in my experience not being able to do this might not be such a bad thing.

Instead I've ended up with a rich set of builders and commands that most of my controllers delegate to. That way I can reuse most of the controller logic while being able to do specific things for API versus the web:

http://www.paulstovell.com/clean-aspnet-mvc-controllers

like image 131
Paul Stovell Avatar answered Sep 28 '22 15:09

Paul Stovell