Web API - Rendering Razor view by default?

后端 未结 5 952
执念已碎
执念已碎 2021-02-13 16:52

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

5条回答
  •  野的像风
    2021-02-13 17:38

    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

提交回复
热议问题