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
Related
MS stack developer historically.
I have committed to retooling to the following stack
angular -> ms web.api2 -> C# business objects -> sql server
Being old, I develop the database from requirements and use Codesmith to generate the business logic layer. (yes, I have heard of entity framework. even tried it once).
As I embrace Angular and web API 2
I find that Angular wants me to write a model on the front end. This seems to be just a data structure, I cant even add helper methods to it
So I also often write a class with helper methods that takes an instance of the model. Kind of ugly,but it does marry structure and logic.
I find that Web API2 wants me to write a model. This again seems to be just a data structure. I am exploring the dynamic data type, but really this doesn't buy me much. Instead of writing a class, I'm writing a mapping function.
The question is this:
Is there any way around having 3+ copies of each class spread across the stack?
Codesmith is a very capable code generator... it can gen multiple files... but...
If its just a couple data members, and 3 places, I can copy paste edit and get it done.
Just seems to me that now committing to keeping a data structure in synch in 3 different environments is setting oneself up for a lot of work.
I have spent the last 15 years trying to shove as much code as I can into a framework of inheritable classes so I can keep things DRY.
Am I missing something? Are there any patterns that can be suggested?
[I know this isn't a question tailored for SO, but it is where all the smart people shop. Downvote me if you feel honor bound to do so.]
Not entirely familiar with how CodeSmith generates it's classes, but if they are just plain-old-CLR-objects that serialize nicely, you can have WebApi return them directly to your Angular application. There are purists that will frown upon this, but depending on the application, there may be a justification.
Then, in the world of Angular, you have a few options, again, depending on your requirements/justification, and your application - again, purists will definitely frown upon some of the options.
create classes that match what's coming down from the server (more correct method)
Treat everything as "any", lose type safety, and just access properties as you need them i.e. don't create the model. (obviously less correct method)
find a code generation tool that will explore API end points to determine what they return, and generate your typescript classes for you.
Personally, using Entity Framework, I (manually) create my POCO's for database interraction, have a "view"/DTO class that WebAPI would then send back to the client, and a definition of the object in Typescript, but I am a control freak, and don't like generated code.
So this is more of a design question, but i think it is one worth questioning.
Here is my dilemma. I am ending up with some quite complex routing while designing an API for consumption. here is an example:
Route("/people/{personID}/phonenumber/{phoneNumberID}/operation/{operationID}/data")
Now this route gets data performed in an operation for a specific phone number for a specific person.
Due to the fact that i can get the operation data solely by the operationID, I really do not need to include personID, or phonenumberID. However this data is tied directly to all of the ID's that are previous to it. Thus, creates "chain of command" if you will.
For instance i could still drop the operationID to get all operations performed on a specific phone number. Like so:
Route("/people/{personID}/phonenumber/{phoneNumberID}/operation")
In this case, the PhoneNumberID is now relevant and needed in order to get the operations neccessary. In the previous example PhoneNumberID did not do anything due to the fact that i had the explict operationID to retrieve data for.
On to my question already!
SO! Should i always include all id's in the route even if they are not needed to actually retrieve the data? Or is this a case of poor design and I should really just rethink how I am doing this? Something just feels off in my gut.
You should try to follow RESTful design. If it's not needed for the resource someone is trying to consume then leave it out. Try to make the API as clear and simple as possible.
If you need to create complex or more detailed API methods you can always have those served via a HTTP POST request for large responses.
Keep things simple. Keep the API clean. Clear well defined Controllers that only take what is necessary for that specific resource.
I've been working on a project now for while which is devied between something we call "webs" (bad name, I know) and "buildings". Each web can have 1 or more buildings, and when you log in you log in to a particular web. Traditionally this was set up as separate vhosts in IIS, thus they were actually separate webs, except for the fact that they all ran the same code-base, however the new system that's being written moves away from this pattern.
Also, in the old system; what building you were currently viewing was stored in a session-variable, in other words one couldn't direct link to anything. Say for instance that you log in to web 01 on building 01 and navigate to the ao_list.asp (the old web was classic asp), you'd end up with an url looking something along the lines of web01.domain.com/ao/ao_list.asp, however in the new system you would have a url like this: domain.com/web-01/building-01/ao/. This ofcause takes you to the Index-method of the AOViewController.
All this work currently, and there is no problem with the navigation at all. In addition to said URL; there is a API-url that closely match the web-url given by domain.com/api/web-01/buildin-01/ao/. This also works great.
But from here comes the problem. Decorating every Controller in the project is the custom AuthorizeAttribute I wrote, that takes into consideration what building/web you are browsing while checking the user right. For instance; no user should have access to web's that isn't their respective user-web. And users can have different rights on different buildings.
The attribute works by getting the building and web-number off from the route-dictionary, then using that when calculating the user-rights, and this works as one would suspect. However, there has been proven a need for API-methods that can aggregate API-calls over several buildings, and I'm struggling trying to figure out how I can implement these.
For instance; whenever a user goes to the start-page of the application; a ajax-requests is made to get a list over outstanding AO's in every building the user has access to. This is currently made one request per building, which might result in hundreds of requests in the worst case scenario. This of-cause is unacceptable, so what I would like would be to be able to do something like calling GET /api/web-01/ao/?buildings=01,02,03,04,06 then loop over the buildings on the server-side and return something like this:
[
{"building":"01","data":<result of calling /api/web-01/building-01/ao>},
{"building":"02","data":<result of calling /api/web-01/building-02/ao>},
{"building":"03","data":<result of calling /api/web-01/building-03/ao>},
etc...
]
And of cause, I would like to simply get an error if any permissions were attempted violated along the way.
Is there a good way I can implement this without having to change the actual implementation of the Index-method on the API.AOController?
Currently I implement buildings by adding a simple look-up in the route-dictionary during OnActionExecuting in a base Controller that all my controllers extend, so what I was thinking was that I could check for the existence of a buildings-querystring-parameter and if it was present create several instances of the current controller, set the building-variable on the "child" controller and call the method in question, but I don't know if this is a good way to do it, and I don't know how to invoke the AutorizeAttribute on the "child" either, so what I'm asking (after writing all this) is a good way to orchestrate this problem in a good way :).
[Edit]
TLDR;
I have a mvc3 page setup with urls like:
domain.com/api/web-01/buildin-01/ao/
domain.com/api/web-01/buildin-02/ao/
etc.
These are all API calls that returns JSON-data after running a custom Autorize-attribute.
What I would like is to be able to do something like domain.com/api/web-01/ao/?buildings=01,02 which would result in getting the accumulated response of the two calls above (grouped by their respective building ofcause) while still running the Autorize-attribute for each building. And if that Autorize-attribute would fail for one of the buildings it the whole request should fail. And also; I would like to be able to do this without having to change the implementation of the Index-method of the AOController, but instead having it called multiple times. I think sort of what I want to achieve is to have a single request "act" as if it was actually several requests, without ofcause creating several requestcontexts (which would spawn database-connections etc.). Is this possible?
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.
In Silverlight, I call my Silverlight-enabled WCF service asynchronously to retrieve, say, a list of values for a combobox. On the server, I cache these values for performance. But I want to cache them on the client to prevent the unnecessary round-trip.
Now, I understand how to use local storage to cache them except that I do not want all of the "if in local storage, return local storage values else get values from server asynchronously" stuff in the code-behind of my xaml app.
So, I tried moving that code to a helper class but the async calls need a callback which is where I get lost. I tried passing a generic EventHandler into my helper class but the helper class method really needs to be static. So, that is throwing me off. Will my helper method need to be non-static, and, if so, do I need to worry about thread safety? Aaarh! Too many questions! Haha. Anyway, I bet some smart person out there can tell me a better way to approach this almost immediately! Thanks in advance.
I've done one major Silverlight app in the past. It has taught me that you shouldn't fight against the system.
If I'm not mistaken, Silverlight itself uses the browser network layer to connect to the internet. So you can still leverage--and Silverlight still respects--things with proper cache-control headers and such.
So just from my experience, I'd suggest that you try to make the server component (WCF server) do proper output-caching ala ASP.NET style and the network layer in Silverlight and the hosting browser will handle caching automatically for you.
You may have better luck with RESTful WCF mode since you can leverage proper HTTP caching throughout, see this blog post: REST in WCF – Part X – Supporting Caching and Conditional GET for a start.
This also makes your code less complex, since you don't have to add yet another complex layer to your system and tame it to work with the confusing XAML binding system.