Asp.net Web API objects definitions - c#

I am working on the asp.net web api where i have to return back objects in json. With respect to making a better approach and easy for (android/ios)mobile developer to consume these Web APIs and parse json objects, what is best approach for making these objects definitions remain shared amongst webapi project and mobile project, so that if we have to change any property then it can easily be reflected on both projects in a better way. It would be great if someone explains it in detail.

There is no such sync method as you are asking.
On your WebAPI server side you'll define the objects and then return them in your API methods. JSON serialization will be automatically handled by the framework, using your serialization engine of choice (i.e. JSON.NET). Remember that with WebAPI you don't decide the output format server side, you just return a response containing the object(s) and then the framework reads the HTTP HEADERS of the request to determine whether the client asked for JSON or XML and then returns what was asked.
The best thing you can do is define a clear API with nice conventions and keep it documented, and if you change anything have the documentation reflect the changes. Avoid making breaking changes, and if you really must, deprecate a property or an object for at least a couple of versions before removing it.
That's the way all public API work anyway.

Related

How can I check changes to existing public api

I have a web api that others are using, and one of our developers changed the name of the action method or method parameter. Now the client has a problem. Is there any solution that, before deploying to the production server, check whether there have been changes in the existing public api (not adding new api)?
I would highly recommend creating a Swagger OpenAPI Specification for your API if you're going to be sharing your API with other teams. A Swagger definition is a specification that describes how your API looks like in terms of actions, expected input, output, etcetera. You can use such a specification as a contract between the producer and all consumers of your API.
Then, you can use tools like Swagger CodeGen to generate clients and server implementations, as a guarantee that an implementation conforms to the contract. In your case, this would prevent a developer from breaking the API (unless they change the contract as well).
If you want to collaborate, I recommend placing (a copy of) your Swagger definitions in a separate GIT repo (e.g. my-awesome-contracts), give all the teams access to this repo and make any changes through pull requests. This serves two purposes:
It gives all the consumers of your API an early notice on any changes
you're planning to make.
It allows any consumers to actually give feedback on the proposed changes.

Updating a complex object in a database via WebAPI Controller, theorycrafting

I have a WebApi Controller for an application under development which is almost complete. There's one method remaining though and I'm not entirely sure which approach to take (decision making by testing input/output is not possible at this very moment due to various reasons unfortunately, therefore all I'm left with is theorycrafting).
Anyway, back to the point. My controller takes a complex model entity, transforms it into a DTO one, with only the values I need taken and then sends it to a smartphone client. That's working fine. My issue is though, I need to create a reverse method as well - something that returns the data gained from the DTO object that's processed client-side and uses it to update the complex entity inside a database. I'm new to both ASP.net and http requests in general.
I'm considering two options : one would be a Post method, although I'm not entirely sure if that could work. Another idea of mine would be a void that simply takes the data and returns it to the database (sounds good on paper, compiles just fine, but I can't test it at this stage as already mentioned, therefore hopefully someone with a deep understanding of the subjects will be willing to help).
(I think putting [HttpGet] above my void method should work, although I might be wrong)
Pardon me if the request isn't clear enough, English is not my native language. (The edit button's here though, so if you can't seem to understand something, let me know)
I think you should be using a PUT/PATCH method; however, I am assuming that you want to update entities, not create them. Using Put/Patch would help to make your application RESTful.
REST is a very popular model for web api's
EDIT :
For reference
POST is CREATE,
GET is READ,
PUT/PATCH is UPDATE,
DELETE is DELETE
That is the making of CRUD to RESTful Web Api's in general

JSON based architecture, how best to synchronise front end and back end

Looking at using JSON for a new .net REST based system and it looks great, but there is one thing thats alluding my understanding. What is the strategy for keeping the JSON on either side of the application in sync?
What I mean by that is if you do a GET for : www.mysite.com/item/12345. Then the .net side of the application goes away to the db, retrieves the Item with id 12345 and resolves it to your object model Item that is then serialised to JSON and returned.
If you do a POST to : www.mysite.com/item and pass -
{
"Id": "12346",
"ItemName": "New Item",
"ItemCost": 45
}
Then the .net side of the application picks it up, deserialises it to an Item object and then hands it off to be added to the db.
How do you get both sides, your JS object model and your .net object model serialisation to sync up? Does this just need to be maintained by hand or is there a clever way of providing a template for the JSON based on the serialisation of the .net model?
I'm kinda just looking for best practices and whats the done thing and don't see how the client side knows what JSON to pass to the server side.
Personally I've found it easier to 'drive' these changes for the .NET environment. Not wishing to teach you how to suck eggs but Javascript is a very loosely bound language means changes / functionality / properties can be added on the hoof whereas in .NET it is far easier to test and stablise your POCOs in a more rigid manner.
One method I have recently toyed with is generating empty POCOs from my service when creating objects, manipulating as appropriate before then pushing them back to the service for persistence, etc. It still doesn't resolve that wild-west like feeling of working in Javascript, but at least the DataContracts can match up on a superficial level.

Using Controllers without the entire MVC Framework

I'm in the process of trying out a few things with MVC whilst designing a system and wanted to try and see if I could use the concept of Controllers outside of the MVC framework. When I say outside, I mean within my own C# service as opposed to a web-site.
I started a simple console application to test the theory and it was simple enough to change the profile to a non-client profile, add in System.Web.Mvc, create a controller and have it return a JsonResult. The ease of which this got set up pleased me as that is half the work done if I want a service to respond with JSON.
The next step is to set up a Http Server class, and I would love it if I could leverage the other part of the framework which will map incoming requests to my controllers. Unfortunately, this is the part where I am lost and I have no idea what code goes on behind to arrive at a particular controller's function with the parameters all in place.
Has anyone got an idea on how to accomplish this, or a resource to look at?
In short: I'd like to leverage the use of Controllers in my own service, running it's own HTTP Server.
You can use the design pattern without using the framework - what I mean is, you can apply the model view controller pattern wherever you believe it solves the problem - if you think that you can replace "view" with "service", you could apply some of the concepts...
http://msdn.microsoft.com/en-us/library/ff649643.aspx
However, there are other patterns that may lend themselves better to services, although if we are talking specifically about a JSON service, then just using the ASP.NET MVC framework as it is would work well (rather than trying to re-write it).
Are you not trying to reinvent the wheel?
If returning JSON is one of your main purpose then WCF fulfills your need. Having WCF with you you are free to host it in IIS. This serves your second purpose having its own HTTP server.
You are trying to achieve some kind of routing where based on URL your different actions will be called. Isn't it similar to having a WCF service with different methods and client is calling each of them with different URL?
Trying controller concept in a non web application seems to be innovative, however in your case it looks like over-engineering.
The basic MVC pattern isn't all the difficult to replicate. I would seriously consider writing your own, rather than trying to shoehorn the MVC classes into your app.
Simon
If it helps you, the entire ASP.Net MVC Framework is open source, you can download it all from http://aspnet.codeplex.com/ . You can use the libraries here to view how the Framework is doing things behind the scenes and adapt things for your own use as appropriate.

Developing a new RESTful web service in .NET -- where should I begin? ASP.NET-MVC, WCF?

The objective is to build a service that I will then consume via jQuery and a standards based web front-end, mobile device "fat-clients," and very likely a WPF desktop application.
It seems like WCF would be a good option, but I've never built a RESTful service with WCF, so I'm not sure where to even begin on that approach.
The other option I'm thinking about is using ASP.NET MVC, adding some custom routes, add a few controller actions and using different views to push out JSON, xml, and other return types.
This project is mostly a learning exercise for myself, and I'd like to spend some extra time and do it "right" so I have a better undertanding of how the pieces fit together.
So my question is this, which approach should I use to build this RESTful service, and what are some advantages of doing it that way?
Normally, I would say WCF for any kind of hosted serice, but in the specific case for RESTful services using JSON as a serialization mechanism, I prefer ASP.NET MVC (which I will refer to as ASP.NET for the remainder of this answer).
One of the first reasons is because of the routing mechanism. In WCF, you have to define it on the contract, which is all well and good, but if you have to make quick changes to your routing, from my point of view, it's much easier to do them using the routing mechanism in ASP.NET.
Also, to the point above, if you have multiple services exposed over multiple interfaces in WCF, it's hard to get a complete image of your URL structure (which is important), whereas in ASP.NET you (typically) have all of the route assignments in one place.
The second thing about ASP.NET is that you are going to have access to all of the intrinsic objects that ASP.NET is known for (Request, Response, Server, etc, etc), which is essential when exposing an HTTP-specific endpoint (which is what you are creating). Granted, you can use many of these same things in WCF, but you have to specifically tell WCF that you are doing so, and then design your services with that in mind.
Finally, through personal experience, I've found that the DataContractJsonSerializer doesn't handle DateTimeOffset values too well, and it is the type that you should use over DateTime when working with a service (over any endpoint) which can be called by people over multiple timezones. In ASP.NET, there is a different serializer that you can use, or if you want, you can create your own ActionResult which uses a custom serializer for you. I personally prefer the JSON.Net serializer.
One of the nice things about the JSON.Net serializer and ASP.NET that I like is that you can use anonymous types with it, if you are smart. If you create a static generic method on a non-generic type which then delegates to an internal generic type, you can use type inference to easily utilize anonymous types for your serialized return values (assuming they are one-offs, of course, if you have a structure that is returned consistently, you should define it and use that).
It should also be mentioned that you don't have to completely discount WCF if developing a RESTful service. If you are pushing an ATOM or RSS feed out from your service then the classes in the System.ServiceModel.Syndication namespace of massive help in the construction and serialization of those feeds. Creating a simple subclass of the ActionResult class to take an instance of SyndicationFeed and then serialize it to the output stream when the ActionResult is executed is quite simple.
Here is a a thought that may help you make the decision between ASP.NET MVC and WCF. In the scenarios you describe, do you expect to need to use a protocol other than HTTP?
WCF is designed to be transport protocol agnostic and so it is very different than ASP.NET. It has channels and bindings, messages, service contracts, data contracts and behaviours. It provides very little in the way of guidance when it comes to building distributed applications. What it gives you is a clean slate to build on.
ASP.Net MVC is naturally a Http based framework. It deals with HTTP verbs, media types, URLs, response headers and request headers.
The question is which model is closer to what you are trying to build?
Now you mentioned ReST. If you really do want to build your distributed applications following the ReST constraints then you would be better to start with OpenRasta. It will guide you down that path.
You can do Rest in ASP.Net MVC and you can do it in WCF, but with those solutions, you will not fall into the pit of success ;-)
Personally, I am not crazy about implementing REST services in WCF. I find the asp.net mvc framework a more natural programming model for this.
The implementor of http://atomsite.net/ originally implemented the atompub specification in WCF and then rewrote the entire service using asp.net mvc. His experience echoed my comment above that for a pure REST service asp.net mvc is the way to go.
The only exception would be if I wanted to potentially expose a service in a restful and non restful way. Or if I was exposing an existing WCF service via REST.

Categories