why should I not use MVC Jsonresult instead of apicontroller get method - asp.net-mvc-5

I have developed an application which was MVC application. It has a requirement that the application will return json data for one get request.
So I have added apicontroller and created a get method to return json data.
So far so good. but then I thought, is it really needed to add apicontroller to create just one get method.
I started exploring and googling what is the difference other than content negotiation. Got lots of answers and articles but non of them were satisfactory.
So here is the actual confusion, why can't I just create a method in the MVC controller with JsonResponse and return the json data(Which I know only is need for my requirement, but other application on different domain will consume it).
Can anyone convince me why should I use apicontroller instead of MVC JsonResponse for my requirement or should I not be using apicontroller at all.
apology if there is any mistake.

If I get it right the question is Can we use MVC action to serve json content answer is yes! Is it okay to use Json Result? answer is It depends where do you want to consume it
Say I am an in a Web Environment where I have no need for the APIs (that means I am not going to serve my data to multiple clients) If that's the scenario where only your View is going to consume data returned from your Action Method you are good to go. An Action returning a Json Result is basically an Action Result and that's what it is made for.
but If you are in a REST scenario and you need your backend to serve your data to the client de facto standard is to use an independent Web API for that.
Controllers' main responsibility should be to work as an intermediary between your View and Model and whatever service layer you want to bring inside it. on the other hand, Web APIs are data-driven there only purpose is to serve data (use them if you need them)
Web APIs are good cause they give you the flexibility of serving the data to possibly any client that might need it. That's what I would pick if I am starting from scratch but if I only need to serve data to one client Controller Action methods will be way to go.
Hope this helps.

Related

Pass parameters from C# function app to another Javascript function app in Azure

I need to set up an application in Azure and make communicate 2 functions (one written in C# and one written in JavaScript).
The C# fragment consists in analyzing a XML feed, get the data and save in objects then finally send them to the other JavaScript function by parameter.
I did read that we could establish communication between both functions using HTTP calls but is it possible to do it with parameters ?
If not, would have any suggestions in order to achieve something like this properly? I'm getting started with Azure and i don't have enough visibility to know what is recommened in such a situation
Thank you for your advices
Yes, this is absolutely possible. How you do this is up to you. If you look at the default HTTP trigger templates, you can see that they take parameters (for example, as query string parameters). You can find more examples in the HTTP and webhook recipes documentation.
You can use other trigger types for cross-function communication as well. Take a look at this documentation for related best practices: https://learn.microsoft.com/en-us/azure/azure-functions/functions-best-practices#cross-function-communication

Sail.js - how to structure JSON based live data output with existing static data in the model

In my Angular app, I want to display a table which contains the following
a) URL
b) Social share counts divided by different social networks
Using Sails.js, I already have the api created for the URL when the results show up, I can display the URL now I'm confused how to get the appropriate social counts showing right besides
Here's the API I'm using: https://docs.sharedcount.com/
by itself, I can see the JSON it produces
But here are my questions:
Should I create a new api (model/controller) for social count data or include it in my model where I have the 'url' action defined?
If I create a new api or include the social_counts as an action in the current, what would my JSON query look like? to retrieve the URL's, I'm using default API blueprint that Sails provides, so:
http://www.example.com/url/find?where={"title":{"contains":"mark"}}
Struggling a bit in terms of the thought process, would be great to get input on this
It depends on your app. is your app will store that data or just consume it? If it need to store, of course you need the API. In purpose for modification or aggregating the data for example.
No, you can't do that. That shortcut method only works if you have the data in your database and let the Sails Waterline ORM and Blueprint API served it.
Perhaps, if you only need to consume the data from that Sharedcount API, you didn't need to use Sails as a backend, in this context. Just use Angular as a client of that API. Except if you need to modify the data first and store it in your own database, so Sails will helps with it's Waterline ORM and Blueprint API.

Use of OData in a web application instead of other

I read in an article that odata can be used for different combination of clients/servers.
Say I would like to develop a web application where i store data(say information about all mobile products on market) using mongoDB and use python as backend with Bottle framework to access data through browser as GET.
Then i decide to extend web app as android app. i can extend it to android without any code change on server side.
My doubt is does using odata here helps in any way? Say if i want to extend it to other clients?
Yes, you are right, you don't need to change even a single line of code on the server side if you change a client app. OData defines many conventions for the communications between the client and the server. such as:
What the URL looks like if you want to query some data
http://services.odata.org/V4/OData/OData.svc/Products?$filter=ID gt 2&$select=ID,Name,Rating,Price&$orderby=Price desc
Which http method should be used to Create/Retrieve/Update/Delete an entity
Generally speaking, Post for Create, Get for Retrieve, Patch/Put for Update, Delete for Delete.
What the payload looks like.
How to invoke a function/action
As long as the requests conform to these conventions, the server side always returns the predictable responsese regardless whether the clients is a browser or a mobile device.
I also find the examples for the odata:
https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ .
Hope this helps you.

Is there a way to link a specific method to a Route in ServiceStack?

The Problem
I'm aware of the basic way to create a route/endpoint in ServiceStack using methods with names like "Get", "Post", "Any", etc inside a service but in the particular case that I'm trying to work with I have an existing service (which I can make an IService via inheritance) that can not be retrofitted w/ServiceStack attributes and currently uses DTOs for the requests and responses.
This service contains many functions that I do not want to manually mask (as this is a pass-through layer) but otherwise already conform to ServiceStack's requirements. What I'm wondering is if there's a way to manually create these routes in a way that would work like I've mocked up here. My existing functions and DTOs already contain the information I would need to define the routes so if this approach is possible it would only require me to enumerate them at initialization time as opposed to generating the services layer manually.
I noticed there is an extension method on Routes.Add that takes an Expression of type Expression> but I was not able to get that working because I believe the underlying code makes assumptions about the type of Expression generated (LambdaExpression vs MemberExpression or something like that). I also may be barking up the wrong tree if that's not the intended purpose of that function but I can not find documentation anywhere on how that variant is supposed to work.
Why?
I'm not sure this is necessary but to shed some light on why I want to do this as opposed to retrofitting my existing layers: The current code is also used outside of a web service context and is consumed by other code internally. Retrofitting ServiceStack in to this layer would make every place that consumes it require ServiceStack's assemblies and be aware of the web service which is a concern I want separated from the lower code. We were previously using MVC/WCF to accomplish this goal but we want some of the features available from ServiceStack.
the current architecture looks like this:
data -> DAL -> discrete business logic -> composition -> web service
Hopefully that makes enough sense and I'm not being obtuse. If you would like any more details about what I want to do or why I'll try to update this post as soon as possible.
Thanks!
You might use the fallback route in order to provide your own routing mechanism.
Then you get the request.Path property and route using your own mapping of path:Function which can be stored in a simple dictionary.
Anyway, if you go this path I don't see much benefit in using servicestack. It seems you just need an http handler that routes requests to existing services.

How can Socket.io and RESTFul work together?

(I'm not familiar to RESTFul, please correct me if my concept is wrong)
In RESTFul architecture, we map every action to an URL. If I click "post a article", may it's actually URL http://example.com/ and some data action=post&content=blahblah.
If I want to post, but not refresh the whole web page, I can use javascript's XMLHTTPRequest. I post it and then get it's content and insert it to a div in my page. These action is all asynchronous.
Then I know there is something named WebSocket and it's wrapper socket.io. It use "message" to communicate between client and server. When I click "post" the client just call socket.send(data) and wait for server's client.send(data). It's magical. But how about URL?
It's possible to use the two model both without repeating myself? In other word, every action has it's URL, and some of them can interact with user real-timely(by socket.io?)
Moreover, should I do this? In a very interactive web program(ex. games), the RESTFul is still meaningful?
You're defining a handler for actions that map to REST over http. POST and GET generally refer to update and query over an entity. There's absolutely no reason you can't just define a handler for generic versions of these CRUD operations that can be used in both contexts. The way I generally do this is by introducing the concept of a 'route' to the real-time transport, and mapping those back to the same CRUD handlers.
You have a session, you can impose the same ACL, etc.
 +---------------------------------+
 |                                 |
 |      BROWSER                    |
 |                                 |
 +--+--^-------------------+---^---+
    |  |                   |   |
    |  |                   |   |
 +--v--+---+            +--v---+---+
 |         |            |          |
 | HTTP    |            | SOCKET.IO|
 +--+---^--+            +--+---^---+
    |   |                  |   |
 +--v---+------------------v---+---+
 |                                 |
 |        ROUTING/PUBSUB           |
 +-+--^-------+--^-------+--^------+
   |  |       |  |       |  |
 +-v--+--+  +-v--+--+  +-v--+-+
 |       |  |       |  |      |
 | USERS |  | ITEMS |  |ETC   |
 +-------+  +-------+  +------+
     ENTITY CRUD HANDLERS
I posted this on my blog recently:
Designing a CRUD API for WebSockets
When building Weld, we are using both REST and WebSockets (Socket.io). Three observations on WebSockets:
Since WebSockets are so free-form, you can name events how you want but it will eventually be impossible to debug.
WebSockets don’t have the request/response form of HTTP so sometimes it can be difficult to tell where an event is coming from, or going to.
It would be nice if the WebSockets could fit into the existing MVC structure in the app, preferably using the same controllers as the REST API.
My solution:
I have two routing files on my server: routes-rest.js and routes-sockets.js
My events look like this example: "AppServer/user/create".
I use forward slashes (“/”) to make the events look like routing paths.
The first string is the target (~”host name” if this actually was a path).
The second string is the model.
The third string is the CRUD verb: i.e. create, read, update, delete.

Resources