Restful WebAPI VS Regular Controllers

2019-08-07 05:08发布

问题:

I'm doing some R&D on what seems like a very confusing topic, I've also read quite a few of the other SO questions, but I feel my question might be unique enough to warrant me asking. We've never developed an app using pure WebAPI.

We're trying to write a SPA style app, where the back end is fully decoupled from the front end code

Assuming our service does not know anything about who is accessing/consuming it:

WebAPI seems like the logical route to serve data, as opposed to using the standard MVC controllers, and serving our data via an action result and converting it to JSON. This to me at least seems like an MC design... which seems odd, and not what MVC was meant for. (look mom... no view)

What would be considered normal convention in terms of performing action(y) calls?

My sense is that my understanding of WebAPI is incorrect.

The way I perceive WebAPI, is that its meant to be used in a CRUD sense, but what if I want to do something like: "InitialiseMonthEndPayment".... Would I need to create a WebAPI controller, called InitialiseMonthEndPaymentController, and then perform a POST... Seems a bit weird, as opposed to a MVC controller where i can just add a new action on the MonthEnd controller called InitialisePayment.

Or does this require a mindset shift in terms of design?

Any further links on this topic will be really useful, as my fear is we implement something that might be weird an could turn into a coding/maintenance concern later on?

回答1:

If you are planning to make your services RESTful, the controller should represent a resource. In your example, the resource is Payment, so the controller would be called PaymentController.

You can have multiple POST methods in the same controller. In your scenario, I would call the action method PostMonthlyPayment or something similar. The URL (routing) would look like http://server.com/api/payment/monthly and the body (assuming JSON) would be something like:

{
   user: user@internet.com,
   month: 10,
   year: 2013,
   // any additional data
}

If the payment goes through, a good practice is to return HTTP error code 201 and the Location HTTP Header containing the URL to the payment GET method. If any data in the body is wrong, return a error code 400. If a payment had already been made by the user, conflict code 409 can work.



回答2:

For SPA you will definitely need REST Web Sevice. My suggestion is to try servicestack instead WebApi