ChatGPT解决这个技术问题 Extra ChatGPT

Using WebAPI or MVC to return JSON in ASP.NET

I'm building an ASP.NET MVC application that is client-script heavy, it will use JSON and jQuery to manipulate the DOM.

My understanding is both Web API Controller and MVC Controller can return JSON.

Given my scenario, should I use a Web API Controller or an MVC Controller?

Important to note is that this question is specific to a certain context: the author wants to know what controller to use if ONLY json should be returned. A REST API allows different media formatting depending on content negotiation (eg: accept xml, accept json). In this case WebAPI controller is your best option

S
Shaun Wilson

Web API Controllers can be created and hosted in any ASP.NET Application, not just MVC applications. Thus, an obvious reason to create a Web API is if you do not have an MVC front-end (e.g. classic, RESTful web-services hosted by your company/organization.)

MVC Controllers typically rely on the MVC Framework, if you look at default templates and most of the work done by the community and your peers you will notice that almost all MVC Controllers are implemented with the View in mind.

Personally, I use MVC Controllers when I intend to respond with a View(), and I'll use a Web API for anything that isn't dependent on a particular view.

There are caveats, of course, but generally speaking if you don't require the Model Binding behavior of MVC, your service is data-centric, and operations are Data-centric (e.g. CRUD operations) then you likely want a 'Web API Controller' instead of a 'Model-View Controller'. Conversely, if your operations are View-centric (e.g. delivering a user admin page to the user), or you need MVC's Model Binding to generate 'ajax partials' (very unlikely), then you will want an MVC Controller instead.

Personally, I use Web API controllers for driving JSON-based RESTful clients, I use MVC controllers for handling basic browser routing and delivery of the SPA.


M
Muhammad Hasan Khan

WebAPI is for making an API. If you want someone to be able to consume your API in XML, JSON, etc. You can make a web api.

In your case you only need to talk to client in JSON.

Even though your website is mostly client script driven you would still be using ASP.NET MVC Controller right? And since you may have already logically divided your controllers based on entities then it make sense to add those json serving methods in it as opposed to making another class specifically for web api.

So for your particular situation (if i understand correctly), I would stick with Controllers.


Thanks, is there a difference in how we create WebAPI vs Controller?
@flybyte yes you need to derive from ApiController, see asp.net/web-api/overview/getting-started-with-aspnet-web-api/…
Web Api can do JSON, as well as the other methods you list. Controllers cant (neatly) be turned into an API, So given the user is having the foresight to ask - I'd suggest using the more scalable/flexible solution. Its not as if its like old school WCF services, web api is generally both powerfull and flexible. So while you only need simple scenarios it stays out of your way. BUt you've got the power should you need it
D
David Klempfner

The answer boils down to separation of concerns, fasten the creation of services and to rely on convention rather than configuration.

Controllers main responsibility is to work as a coordinator between view and your model but where as API's main responsibility is to work on data. In the case of API's conventions make it really easy to perform CRUD operations. Below is the mapping between CRUD operation and HTTP actions

GET : Read

POST: Create

PUT: Update

DELETE: Delete

So with APIs you do not have to create separate actions and attribute them with HTTP actions.


R
Ramon Chan

The only concern I have with ApiController is that it is site-based not area-based. One site can only have one apicontroller subfolder for you to name your controller methods. There are situations you might want to duplicate controller name in different areas :

domain.com/api/area1/controller1/

domain.com/api/area2/controller1/

I remember there are some custom code settings to be able to do this but it does not work by default.


this seems like a comment, not an answer.
Don't no really what you are saying. If you name a controller Area1XController then you can do: domain.com/Area1X/1, create a controller: Area2XController and then access it with: domain.com/Area2X/1. The big question is why you want to do that anyway. Area name is abstract it says nothing to a user. If you have lets say 4 Areas then its better to use the functional purpose name for it.
R
R.H. Thorne

I agree with Shaun Wilson's (top answer) answer but not sure why as I am just a bit confused and still trying to understand with the following (probably incorrect) premonition -

Use WebAPI Controller to deliver JSON data to the client so that the client can handle the view manipulation. This process doe NOT require a view but rather just a response back to whatever called the method (i.e. a javascript request) so that the client can handle any client-side manipulation.

Use MVC controller when you need to use the data to manipulate a view during or right after page_load (i.e. not for SPA apps).

You see, I just don't know how I am incorrect here and am confused because the last line of Shaun's answer states "I use MVC controllers for handling basic browser routing and delivery of the SPA." - perhaps I do not fully know what a restful client is when I assumed it could be JavaScript method that receives an response in JSON form. this is the closest post in Stackoverflow that was remotely related as an answer to my question so I'm answering this post instead of possibly duplicating questions.


"Use MVC controller to deliver the View" you can wrap the SPA into MVC partials for composition into a View. ASP.NET MVC devs should understand this concept. You can utilize regular Razor+ASP.NET facilities during view generation (e.g. server-side processing) to render HTML+JS to the client. the problem many devs will experience here is the idea that static HTML+JS files aren't what make an SPA an SPA. sometimes content needs to be dynamic, and specific to the user, but all frameworks tend to detract from this fact. "SPA" and "MVC" are not mutually exclusive.
j
jezzipin

In this scenario, I would recommend WebApi as it's perfect for transferring data such as this based upon Javascript requests. I will usually develop my WebApi controllers so that they return a JSON friendly object that can then be parsed easily by my Javascript.

The only real time where you would want to use an action on an MVC controller for this sort of thing would be if you wanted to generate some HTML and replace segments of your page with Javascript calls.

For example:

You have a JQuery UI Datepicker that upon selection generates a list of radio buttons that represent events on the chosen day.

In this scenario, you could use WebApi to return some JSON and then generate the necessary HTML using Javascript but generally it's bad practise to create a lot of HTML using Javascript. It would be much better to have C# build up the HTML and then return it via a partial view as this way you are less likely to encounter errors with Javascript parsing. Not to mention it makes the HTML a lot easier to write.