I'm checking out Web API and I'm not sure how asp.net mvc and web api can or should work together.
I want to implement Backbone on the client side, but I'm not sure if I should implement an ApiController or a normal Controller on the server side?
The way I'm doing things (Getting current user / account information) is that a base ApiController will have some of the same functionality as a base Controller would, which would lead to a bit of duplicate functionality, but not sure what would be the other trade offs.
Or would you only create an ApiController for a public service that you want to provide and stick to Controllers for the web app?
If you're planning an API, use the ApiController. If you're doing Web UI stuff, use the classic Controller. That's what both are made for.
This is almost exactly the situation I am in, except that I am using Knockout.js rather than Backbone. I have views for Create and Edit and within each view, a very complex Knockout.js UI which does loads of Ajaxing of JSON back and forth to the server.
Under MVC3 I was using numerous JsonResult methods within the same controller which rendered the views. I've been experimenting with the RC of MVC4 and was pondering whether to go down the "route" (ho ho) of using an API controller for the Ajax requests. I like the strongly typed HTTP classes and the fact that JSON.NET is more integrated, but at this stage, I have to say that the end result of having a separate API controller for my own internal use just didn't feel right. Like you, I found that I ended up with a lot of duplication around security, and the separation of what was related logic simply by content type made things more confusing rather than cleaner.
So at this point (although I have been known to be fickle) I plan to keep using standard MVC controllers for my current context, but I'll jump at a chance to use the shiny new Web API if I end up exposing a public API.
Related
I am working on a project that has MVC 4 and the Umbraco CMS installed. I apologise - being newbie, my question may be weird.
My question is: how do I work with types which I don't want to manage through Umbraco back office?Rather, it will be simple data coming and being stored in SQL Server.
Specifically I want to ask:
Can I create a controller in MVC and bypass Umbraco?
What controllers should be inherited from? Should they be standard MVC Controller, SurfaceController or RenderMvcController? Again, it will not be an Umbraco document type or data.
Will views be inherited from UmbracoViewPage, UmbracoTemplatePage or it can be a standard MVC view?
How will the URL of these views, controllers and actions change? In Umbraco, the URL depends on the content tree, but how it will be with non Umbraco controllers, views and actions?
Thank you so much for your precious time, guidance, sharing and help; I highly appreciate it.
You are asking a lot of different questions here.
When developing with umbraco Umbraco it's not uncommon to embed external data into your website. If we already tell you that you can use (almost) any type of dataaccess you use in plain .Net projects.
Don't loose your umbraco context
It's important when pulling in external data (e.g.) products, that you don't loose your umbraco context. You still have a breadcrumb to render, css classes for active menu's to set and so on. Your "external data" belongs probably below a node. Therefor it's a bad idea to use Standard MVC controllers.
Dirty razor
Because your views are in razor, you COULD put every extraction of external data into #{ ... } in your view. If you are not an experienced programmer, this works. Although topics about maintainablility and DRY principles are questionable :-)
RenderMvcController versus SurfaceController
When you use a RenderMvcController you basically are are creating a Controller for a specific document type. Each time umbraco is rendering a node of this document type. This controller will be invoked and the model you render is send back to the View. As you might guess, this is one of my favorite places to extract data and push it to the view.
A surface controller on the other hand is a controller for a partial view, extremely well in handeling form postbacks.
Both of these controllers can be used for the front-end of your website, not for the backend.
Inherit your views
You can do with your views what you want. But if you inherit your view from UmbracoViewPage you still have all the #Umbraco.Whatever power available in your views
Your URLS stay the same
Because you "hijack" a route using the RenderMvcController, you can just trust the umbraco backend to go to the right URL. The querystring can be used to get external data you want.
Other controllers or methods
Sometimes, if I can't use the controller above, I create an extentionMethod on the IPublishedContent. Like that I can write code like this:
foreach (var myObj in Model.Content.GetMyExternalData()) {
// do stuff
}
Of if you need to expose data (using a webApi wrapper), try the UmbracoApiController. This REST pure sang.
Data Access in umbraco
You should know that Umbraco uses petapoco as ORM. Therefor you can (and should) consider to use it too. You can reuse the database connection without any problems.
var query = new Sql().Select("*").From("myCustomTable").Where<MyModel>(x => x.Id == id);
return DatabaseContext.Database.Fetch<MyModel>(query).FirstOrDefault();
I need to create a website where some of it's pages should be accessible from external clients via an API, but I still want to make regular MVC Razor views to retrieve, display and manipulate the same data.
What's the best way to achieve this?
Update
What the API will have to expose is just data manipulation.
For the web pages, I still want to benefit from the razor chtml views, I prefer not polluting my views with redundant jQ or JS nor data- attributes that consume the data.
Just create an MVC project with the pages you want, and then create ApiControllers (from the Web API framework) to serve as RESTful endpoints. You can program your views to retrieve data from the API actions as JSON objects, and consume them with javascript. Other people can hit the same API actions and use the data in some other way.
If you want to start with a WebApi, and build basic views based on the same data that someone else could access via that API, you could inject your WebApi controllers into your normal MVC controllers, and invoke their methods to get the data that you need to build your ViewModels. This should work all right as long as your API controllers don't need to do anything "outside the box" like inspecting the Request object directly.
A more robust method would be to create a "Manager" layer that handles all the business logic of your application, and then have your ApiControllers be nothing but thin wrappers around calls to their respective Manager classes. This would add a little maintenance cost, but it would adhere to the Single Responsibility Principle a little better.
The easiet way is to use just MVC.
You can also combine MVC + WebAPI in one site.
The reasons to go with the first option is simplicity, and learning maintaining one framework and one set of abstractions.
However if you have any of the following requirements, adding Web API becomes interesting:
1. You want to do content negotiation for response types (say XML vs. Json for the same action).
2. You want to support CORS
3. You want a help page for your API.
4. You want to structure your Url space for your API with rest and resource centric approach (basically GET /resource rather than /resource/GetData).
5. Easier to unit test controllers and actions.
Both frameworks are built by the same team, they both support attribute routing and many similar concepts, and both work well together with one another. I've seen folks take both approaches successfully. Also note that visual studio has templates that combines both of them from the get go.
TL;DR
What are the best practices when using .NET Razor views and AngularJS?
Context
We are developing a public website (not an intranet application) using mvc4 with razor, and we weren't very familiar with client script, so we started with what we knew: jQuery.
But now things are getting more complicated and we'd like to switch to AngularJS.
On the .NET part, we use Razor templates and UIHintAttribute (plus some custom ones) to render the right html "control". We also add custom html attributes to give extra information to the jQuery part (like title for a tooltip....)
So we already use a declarative way of setting the user interface behavior, that's why AngularJS seems a good option.
Questions
Since we already have models defined server side, and since AngularJS also uses models, wouldn't it force us to duplicate code?
How do we deal with data binding feature, since we already do some binding server side (in the views). Should we make a completely asynchronous application, making AJAX calls from AngularJS to load data, or can we mix both?
Anything else we should be aware of when trying to use both of these technologies?
I did some research on Google, but I can't find detailed ways of mixing Razor views and templates with AngularJS... Perhaps that's just not a good thing to do?
We dealt with this issue for months when working with MVC plus another JavaScript framework (Knockout). Ultimately, if you're going to be using a client-side MV* framework for rendering your user interface, you will find that mostly ditching Razor is going to be your best bet.
Most of the major MV* JavaScript frameworks, including AngularJS, assume you will be maintaining UI state and rendering your user interface based on JavaScript models or view models. Trying to mix in server-side rendering is just not going to work very well.
That's not to say there is no use for MVC when it comes to developing an Angular application. You can still take advantage of some great features like ASP.NET Bundling and Minification. And sometimes it works really well to embed JSON directly into the page using a Razor view or partial as opposed to making an additional AJAX call.
As for models, you may want to take a look at Breeze.js. It's a JavaScript library for data access that goes great with ASP.NET on the server side to share model metadata.
We wrote our own data binding mechanism that synchronizes the angular.js model with a view model on the server side. The javascript model is generated from a JSON serialization of the server-side view model to avoid the duplicate code that you were talking about.
We are using SignalR to update the client's view model from the server.
Server-side changes of the C# view model properties are sent to the client as a packet containing the path to the property, e.g. Persons[42].Address.City, and the value itself, e.g. New York. The view model inherits a base class that takes care of generating the property path, so the actual view model looks quite clean and we can concentrate on business logic.
Client-side changes of the javascript view model properties are sent to the server in the same way. To catch the change events, we encapsulate all fields of the original javascript model in get/set properties where the setter sends the update packet to the server.
Server-side methods of the view model can be invoked in a similar way. All objects in the view model have an invokeMethod function that can be used like this: Products[42].Manufacturer.invokeMethod('SendEmail', 'mailsubject', 'mailbody'). This will send a packet to the server containing the method path Products[42].Manufacturer.SendEmail and the arguments as an array of ['mailsubject','mailbody'].
In conclusion, the html view (kind of) binds to the view model on the server side where other systems, such as regular Razor views can work on the same objects.
The source code can be found here: SharpAngie.
I'm writting an application that has many Ajax widgets (Kendo-UI to be percise). It's starting to get messy to have all those Ajax responses without the standard controllers so I was starting to consider making each entities their own controller. If I'm taking the time to do this, I figured I might as well go foward and do those as WebAPIs since I was planning to do this in a not so close future, but hey, it would be done already...
So my question is: Is it a good practice to use an MVC application's own Web API as a Ajax Widget feeds or is there any reason to stick with standard Controllers?
I've seen some arguments about performance, but I don't think this applies to this situation. I believe it was more of a "Controller calling WebAPI" situation which has obvious performance hits. But since it's already a client side Ajax call, weither it goes into a standard MVC Controller or a WebAPI controller shouldn't change a thing, would it?
Edit
Additional information regarding the project:
I am using Entity Framework for the data access.
I have a repository pattern going on with UnitOfWork.
I am using proper a MVC structure (EF POCOs AutoMapped to DTO POCOs in the repository and fed into View Models by the controllers)
This is a MVC 4 project on .NET 4.0
There is a lot of database relationships (specially for the object I'm working with at the moment)
I don't know about "good practice", but it's certainly not "bad practice". I see no difference whether you do it in the app or a different one.
I think its a good thing but only if what you are doing in the API is kept as generic as possible to other applications and services can reuse the API.
Both the applications I have written and continue to maintain use pretty much the exact same stack as your app.
I have recently re-factored one of the applications to use the API for all the common things like lists that I'm binding to Kendo ComboBoxes etc. in my views. Its a fairly large application that re-uses a lot of the same lists such as states, priorities, complexities across various Entities and views so it makes sense to put those in the API.
I haven't gone as far as going the whole hog through. I draw the line with things like this:
public ActionResult GetAjaxProjectsList([DataSourceRequest]DataSourceRequest request)
{
return Json((DataSourceResult)GetProjectsList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
That is very specific to how the Kendo Grid wants the data back. Nothing else I have connecting to this app will use this data in this format so I keep it in the controller.
In short... I use the API for common things within the same MVC app and things that I allow to be used by other applications or services, like Excel.
How do I get Web API to render a Razor view using the model that it returns? And only XML/JSON when the accept headers (or .extension) is set? Is this even possible?
It seems crazy to require one set of controllers for rendering HTML and another for JSON/XML if they're working on the same models.
Update Darrel Miller has already written a ViewEngineFormatter for Razor which might do the trick, though haven't tried it yet.
I asked a similar question about this in the past on StackOverflow, because I wanted to do the same thing. However, I eventually ended up with an "Api" area and set of controllers, and a standard set of MVC controllers for the website.
In hindsight this actually wasn't a bad thing. I've found I tend to do different things in each set of controllers anyway. My views aren't just CRUD but tend to contain extra contextual data, so returning view models specific to that page is nice.
I think if I had stuck to my goal of combining the two I might have ended up with either over-complicated controllers or a user experience that wasn't as optimal as it could have been. So while this isn't a direct answer to your question, in my experience not being able to do this might not be such a bad thing.
Instead I've ended up with a rich set of builders and commands that most of my controllers delegate to. That way I can reuse most of the controller logic while being able to do specific things for API versus the web:
http://www.paulstovell.com/clean-aspnet-mvc-controllers
Yes, it is how it is designed for: Web API for data and MVC for rendered views. I know that some people will try adding view engine support to web API but it is not designed for it.
My personal view on this is that this parallel world between MVC and Web API (which is the source of most criticisms while community has generally praised the product) is mainly a consequence of the fact that Web API has been added to MVC without having a reference (or knowledge of it).
As Jon Galloway said on a recent podcast, had the team have HTTP knowledge they have now (as well as hindesight of the popularity of REST API now which they did not have then), they would have designed just a single pipeline serving data and rendered view alike.
I can only speculate that the future version of MVC/Web API will be presented as a single pipeline. In fact, this parallel world might have been a careful plan to unify them in the near future.
It seems crazy to require one set of controllers for rendering HTML
and another for JSON/XML if they're working on the same models.
AFAIK, that's how it is. Standard controllers should be used for rendering HTML and ApiControllers for JSON/XML.
It seems crazy to require one set of controllers for rendering HTML
and another for JSON/XML if they're working on the same models.
Web API is exactly what it is called - a technology for creating API's.
If you are creating an ASP.NET MVC application and want to return some JSON for your own purpose then you don't need content negotiation etc. therefore you don't need Web API (just use plain old good JsonResult).
If you want to create a reusable API than Web API is what you need but your client application should consume it in the same way as everybody else.
Web API isn't meant to be a "hammer" for "nailing" all non-HTML requests - use it when you need it.
I am looking for something similar to this, but not entirely. Through scouring the web, I found a couple posts by Fredrik Normen. He writes about this exact problem space and actually identifies a third-party solution in the second post listed. Basically, the solution involves creating a custom MediaTypeFormatter that knows how to handle views using the Razor engine provided by Microsoft (through the use of a third-party library).
Using Razor engine together with Asp.Net Web API to create a
Hypermedia API
Using Razor together with ASP.NET Web API
ASP.Net Web API and using Razor the next step
Hopefully Microsoft will implement something soon in Web API as Hypermedia seems to be gaining traction.
Hope this helps!