Is there a method to cache Razor page in Service Stack? - asp.net-mvc

I'm new to Service Stack, just discovered and looks very interesting to use.
I'd like my future websites to be quite backbone heavy but still ensure they can mostly be indexed by Google and seen by people with JavaScript (more for Google indexing)
I know there is content caching, such as lists etc which can be retrieved and severed the a razor page.
But I didn't see any methods of docs covering caching the entire razor page after being rendered, which is what I believe OutputCache attribute does on normal ASP.NET MVC 3.
So if anyone could direct me to possible examples of entire razor pages being cached using Service Stack, or a possible method of doing it would be greatly appreciated.
Thanks

Caching Razor/HTML views in ServiceStack is done in the same way as every other format by using ToOptimizedResultUsingCache e.g:
public object Any(CachedAllReqstars request)
{
if (request.Aged <= 0)
throw new ArgumentException("Invalid Age");
var cacheKey = typeof(CachedAllReqstars).Name;
return RequestContext.ToOptimizedResultUsingCache(Cache, cacheKey, () =>
new ReqstarsResponse {
Aged = request.Aged,
Total = Db.GetScalar<int>("select count(*) from Reqstar"),
Results = Db.Select<Reqstar>(q => q.Age == request.Aged)
});
}
This service caches the output of any requested format, inc. HTML Razor Views.

Related

How can I write an MVC3/4 application that can both function as a web API and a UI onto that API?

My title sums this up pretty well. My first though it to provide a few data formats, one being HTML, which I can provide and consume using the Razor view engine and MVC3 controller actions respectively. Then, maybe provide other data formats through custom view engines. I have never really worked in this area before except for very basic web services, very long ago. What are my options here? What is this Web API I see linked to MVC4?
NOTE: My main HTML app need not operate directly off the API. I would like to write the API first, driven by the requirements of a skeleton HTML client, with a very rudimentary UI, and once the API is bedded down, then write a fully featured UI client using the same services as the API but bypassing the actual data parsing and presentation API components.
I had this very same thought as soon as the first talk of the Web API was around. In short, the Web API is a new product from the MS .NET Web Stack that builds on top of WCF, OData and MVC to provide a uniform means of creating a RESTful Web API. Plenty of resources on that, so go have a Google.
Now onto the question..
The problem is that you can of course make the Web API return HTML, JSON, XML, etc - but the missing piece here is the Views/templating provided by the Razor/ASPX/insertviewenginehere. That's not really the job of an "API".
You could of course write client-side code to call into your Web API and perform the templating/UI client-side with the mass amount of plugins available.
I'm pretty sure the Web API isn't capable of returning templated HTML in the same way an ASP.NET MVC web application can.
So if you want to "re-use" certain portions of your application (repository, domain, etc), it would probably be best to wrap the calls in a facade/service layer of sorts and make both your Web API and seperate ASP.NET MVC web application call into that to reduce code.
All you should end up with is an ASP.NET MVC web application which calls into your domain and builds templated HTML, and an ASP.NET Web API application which calls into your domain and returns various resources (JSON, XML, etc).
If you have a well structured application then this form of abstraction shouldn't be a problem.
I'd suggest developing your application in such a way that you use a single controller to return the initial application assets (html, javascript, etc) to the browser. Create your API / logic in WebAPI endpoint services and access those services via JavaScript. Essentially creating a single page application. Using MVC 4 our controller can return different Views depending on the device (phone, desktop, tablet), but using the same JavaScript all of your clients will be able to access the service.
Good libraries to look into include KnockoutJS, SammyJS , or BackBoneJS
If you do have a requirement to return HTML using the WebAPI e.g. to allow users to
click around and explore your API using the same URL then you can use routing\an html message handler.
public class HtmlMessageHandler : DelegatingHandler
{
private List<string> contentTypes = new List<string> { "text/html", "application/html", "application/xhtml+xml" };
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Get && request.Headers.Accept.Any(h => contentTypes.Contains(h.ToString())))
{
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
var htmlUri = new Uri(String.Format("{0}/html", request.RequestUri.AbsoluteUri));
response.Headers.Location = htmlUri;
return Task.Factory.StartNew<HttpResponseMessage>(() => response);
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
For a full example check out:-
https://github.com/arble/WebApiContrib.MessageHandlers.Html
I've played with this idea before. I exposed an API through MVC3 as JSONResult methods on different controllers. I implemented custom security for the API using controller action filters. Then built a very AJAX heavy HTML front-end which consumed the JSON services. It worked quite well and had great performance, as all data transferred for the web app was through AJAX.
Frederik Normen has a good post on Using Razor together with ASP.NET Web API:
http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx
One important constraint of a well designed REST service is utilizing "hypermedia as the engine of application state" (HATEOAS - http://en.wikipedia.org/wiki/HATEOAS).
It seems to me that HTML is an excellent choice to support as one of the media formats. This would allow developers and other users to browse and interact with your service without a specially built client. Which in turn would probably result in the faster development of a client to your service. (When it comes to developing actual HTML clients it would make more sense to use a json or xml.) It would also force a development team into a better designed rest service as you will be forced to structure your representations in such a way that facilitates an end users navigation using a browser.
I think it would be smart for any development team to consider taking a similar approach to Frederik's example and create a media type formatter that generates an HTML UI for a rest service based on reflecting on the return type and using conventions (or something similar - given the reflection I would make sure the html media format was only used for exploration by developers. Maybe you only make it accessible in certain environments.).
I'm pretty sure I'll end up doing something like this (if someone hasn't already or if there is not some other feature in the web api that does this. I'm a little new to Web API). Maybe it'll be my first NuGet package. :) If so I'll post back here when it's done.
Creating Html is a job for an Mvc Controller not for Web Api, so if you need something that is able to return both jSon and Html generated with some view engine the best option is a standard Mvc Controller Action methosd. Content Negotiation, that is the format to return, can be achieved with an Action Fiter. I have an action filter that enable the the controller to receive "hints" from the client on the format to return. The client can ask to return a view with a specific name, or jSon. The hint is sent either in the query string or in an hidden field (in case the request comes from a form submit). The code is below:
public class AcceptViewHintAttribute : ActionFilterAttribute
{
private JsonRequestBehavior jsBehavior;
public AcceptViewHintAttribute(JsonRequestBehavior jsBehavior = JsonRequestBehavior.DenyGet)
{
this.jsBehavior = jsBehavior;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string hint = filterContext.RequestContext.HttpContext.Request.Params["ViewHint"];
if (hint == null) hint = filterContext.RequestContext.RouteData.Values["ViewHint"] as string;
if (!string.IsNullOrWhiteSpace(hint) && hint.Length<=100 && new Regex(#"^\w+$").IsMatch(hint) )
{
ViewResultBase res = filterContext.Result as ViewResultBase;
if (res != null)
{
if (hint == "json")
{
JsonResult jr = new JsonResult();
jr.Data = res.ViewData.Model;
jr.JsonRequestBehavior = jsBehavior;
filterContext.Result = jr;
}
else
{
res.ViewName = hint;
}
}
}
base.OnActionExecuted(filterContext);
}
}
Now that it's been a little while through the Beta, MS just released the Release Candidate version of MVC4/VS2012/etc. Speaking to the navigation/help pages (mentioned by some other posters), they've added a new IApiExplorer class. I was able to put together a self-documenting help page that picks up all of my ApiControllers automatically and uses the comments I've already put inline to document them.
My recommendation, architecture-wise, as others have said as well, would be to abstract your application into something like "MVCS" (Model, View, Controller, Services), which you may know as something else. What I did was separate my models into a separate class library, then separated my services into another library. From there, I use dependency injection with Ninject/Ninject MVC3 to hook my implementations up as needed, and simply use the interfaces to grab the data I need. Once I have my data (which is of course represented by my models), I do whatever is needed to adjust it for presentation, and send it back to the client.
Coming from MVC3, I have one project that I ported to MVC4, which uses the "traditional" Razor markup and such, and a new project that will be a single page AJAX application using Backbone + Marionette and some other things sprinkled in. So far, the experience has been really great, it's super easy to use. I found some good tutorials on Backbone + Marionette here, although they can be a bit convoluted, and require a bit of digging through documentation to put it all together, it's easy once you get the hang of it:
Basic intro to Backbone.js: http://arturadib.com/hello-backbonejs/docs/1.html
Use cases for Marionette views (I found this useful when deciding how to create views for my complex models): https://github.com/derickbailey/backbone.marionette/wiki/Use-cases-for-the-different-views

Rich web app using ASP.NET MVC and Backbone.js and progressive enhancement

I'm working on a small web app using mvc and backbone.js and I have a couple of thoughts about how to handle async request vs regular requests.
Today I use a controller called /pages which returns a partial view if it's a ajax request and a standard view if it's a regular request. In another question I was told I'm doing it all wrong when I send a bunch of HTML back to the client.
So how should I structure my controllers etc to handle both async and non async requests?
In my case I have the following code in my pages controller
public ActionResult Index() {
var id = _model.Id;
var parentId = _model.Parent != null ? _model.Parent.Id : null;
var viewModel = new IndexViewModel
{
RootModel = _session.Query<IPageModel>().SingleOrDefault(model => model.Parent == null),
CurrentModel = _model,
ParentModel = parentId != null ? _session.Load<IPageModel>(parentId) : null,
Children = _session.Query<IPageModel>()
.Where(model => model.Parent.Id == id)
.Where(model => !model.Metadata.IsDeleted)
.OrderBy(model => model.Metadata.SortOrder)
.ToList()
};
if(Request.IsAjaxRequest()) {
return PartialView(viewModel);
}
return View(viewModel);
}
But if I understand things correctly I would be better off sending back a collection of pages instead of a complete view model? How should I handle this in my controller?
Is it a good idea to create a separate controller/api using eg. the api controller in mvc 4?
If you are using Backbone then you should return JSON insted of the PartialView and the PartialView should be a template in the page where the Backbone view will render that.
As mentioned earlier in different answers you should return JSON result instead of HTML view.JSON Result on MSDN Example of using JSON result
If you are using ASP.NET MVC 4 (as of now beta) you can use web api to get data in JSON through ajax/rest call.
I agree with Florim. You should be returning json from your MVC controllers. Backbone was built with REST in mind. Therefore your server should mimic a REST API, and return json for Backbone to work with. When I work with MVC 3 and Backbone, all my server code does is return the data. It usually has one view and that is the Backbone Application View. The web app "views" are rendered using templates from the data that is returned from my controllers. Hope this helps.
I have not played with the MVC 4 Web API as of yet, but I do think this situation would be the ideal choice for it.
I've compiled a couple of Backbone examples together into a working ASP.net MVC 3 application that is using REST interface. Here is the link to my tumblr Blog where I have provided information to the source code and the websites I used as resources. Backbone.js works really well with MVC 3 and I am always looking for new ways to push this example.

Retrieving and caching HTML from website using ASP.NET MVC 3

I want a partial view that display some stuff from a website that is not under my control.
The data on the website is only available through HTML, and thus I can only retrieve it by querying the web site and parsing the HTML. (The website holds a list of 50 elements, and I only want the top 10.)
Now, the data from the website is not changing very frequently, so I imagine that I can retrieve the HTML on an hourly basis, and displaying a cached version on my web site.
How can I accomplish this in ASP.NET MVC 3?
Ignoring the MVC3 requirement for now, you should look to using WebClient to grab the html from the website. You can do something like:
var client = new WebClient();
var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com"));
If you need to tailor your request, I'd recommend looking at HttpWebRequest, HttpWebResponse. Now that you can grab the html, you need to consider your caching mechanism, possibly in the ASP.NET runtime?
public ActionResult GetHtml()
{
if (HttpRuntime.Cache["html"] == null)
GetHtmlInternal();
return Content((string)HttpRuntime.Cache["html"], "text/html");
}
private void GetHtmlInternal()
{
var html = // get html here.
HttpRuntime.Cache.Insert("html", html, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration);
}
The first solution that comes to mind is to create an action in a controller that makes an Http request to the remote web page and parses the html you want to return to your own page and then set output caching on your action.
Edit:
What controller to put the action in would depend on the structure of your web site and whether the partial view would be visible on all views or just a specific view. If the partial is visible in all views I'd either place it in the Home controller or create a "General" controller (if I anticipated more actions would go in such a controller).
If you want to manipulate the result I would probably make a model and partial view for the list. If you want to take a part of the returned html and output it as it is I would use the same method as in the answer by Matthew Abbott:
return Content(yourHtmlString);
The end would look something like this:
[OutputCache(Duration = 3600)]
public ActionResult RemoteList()
{
var client = new WebClient();
var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com"));
// Do your manipulation here...
return Content(html);
}
(Some of the above code was borrowed from the post by Matthew Abbott.)
You could just add OutputCache attribute on your action and set OutputCache.Duration Property to 3600 seconds (1 hour)

Client-side partial page rendering and search engines

I'm beginning to write what may grow to be a large commercial website. The business has several facets, so I'm considering a 'widget' based UI not dissimilar to the BBC homepage (http://www.bbc.co.uk).
I'm writing a content management system that would allow an administrator to compose pages using a selection of pre-defined widgets (i.e a text widget, a product widget, news headlines widget etc). I'm writing the application using ASP.NET MVC.
The mark-up for each widget type will be encapsulated in a user control (ascx). I'm considering two approaches for rendering the widgets (which I may mix):
Use RenderPartial to build the page up on the server (very much like the Kona sample from the ASP.NET MVC site)
Render widget place-holders on the served page then get the client to issue a request for each place-holder (using a jquery to call standard MVC actions returning HTML).
The second approach is appealing for two reasons:
It allows for a page to be returned without having to wait for slow-to-render widgets (like a comments widget, perhaps).
It allows me to control caching at a widget level (rather than at a page level). I can use the built-in OutputCache attributes to individually control the type of caching on each widget type.
Here's the question:
If some of the content of a page is only rendered by javascript-initiated HTTP GET requests (i.e. not included in the initial response), would this content be included in Google's appraisal/indexing of the page?
Assume that the javascript requests are triggered on document.ready
For those who like code, my prototype implements the second approach using this code at the server:
[OutputCache(Duration = 30, VaryByParam = "widgetUniqueKey")]
public ActionResult RenderWidget(int widgetId)
{
var cmsService = new CmsService();
var widget = cmsService.GetWidget(widgetId);
string viewName = widget.Accept(new ViewNameWidgetVisitor());
object viewData = widget.Accept(new ViewDataWidgetVisitor());
return View(viewName, viewData);
}
with this code on the client (the initial page GET has returned placeholder divs)
$('.widgetPlaceholder').each(function() { renderWidget(this) });
function renderWidget(source) {
var placeholder = $(source);
var widgetId = placeholder.attr('id').replace("widget", "");
var widgetUniqueKey = placeholder.children('div.uniqueId').text();
$.get('/home/RenderWidget', {
widgetId: widgetId,
widgetUniqueKey: widgetUniqueKey
},
function(data) {
placeholder.replaceWith(data);
}, "html"
);
}
The widgetUniqueKey will vary between widget types: it may be the product id for a product widget; the user id for a recommendations widget; etc.
Many thanks
No. The google bot (and any other indexers as far as I'm aware) doesn't execute any javascript code, so anything that you fetch via ajax won't be indexed.

Where should the browser types be segregated in an ASP.NET mobile MVC application?

I am building what will primarily be a mobile browser targeted ASP.NET MVC application. Although it will target the desktop as well in a smaller capacity. (I'm fairly new to both MVC and mobile apps.)
I'm wondering what is the best practice for segregating mobile vs. desktop users in an MVC application.
Should the controller be in charge of checking for browser type? Or, should this type of functionality be reserved for the View?
If checked in the view, can & should a masterpage do the checking? Do you know of any good examples online?
Update:
I just discovered an overload of the View method that accepts a string argument specifying the Masterpage to be used.
For example:
public ActionResult Index()
{
if (isMobile())
return View("Index", "Mobile", myObject);
else
return View("Index", myObject);
}
To me this suggests that at least a few people on the Microsoft team expect major distinctions (such as mobile vs. desktop) to be carried out in the controller. (There's a good chance I'm highly confused about this.)
I think the controller must know the plataform, because you can get a lot of views in distint languages, Some view for browsers (mobile) another view in Desktop App, another view can be a web service, and all views can have different needs.
If you have a few views, you can call views with parameters to mark the type of view:
Index(mobile) and Index(Desktop) as it:
Index(string typeOfApp){
//prepare data, do querys, etc
if (typeOfApp=='Mobile'){
redirectoAction('IndexMobile',ds);
//or
return view('IndexMobile',ds)
}
return View('IndexDesktop',ds);
}
IndexMobile(DataSet ds){}
IndexDesktop(DataSet ds){}
You can get a general method for your action() and another action for every type,
Index -> Index4Mobile & Index4Browser & Index4Desktop
And in all of this methods prepare or do something special for every plataform, or a Single Action with multiple views(1 for plataform).
Any code dealing with rendering of your code should exist on the page itself via CSS and javascript. Your controllers should know nothing about how your data will be rendered on screen. The views shouldn't really even know anything about it either - they only expose the data that your CSS will render.
The HTML your View spits out describes your data and how it is organized. Only the CSS should know how to make it look appropriate for whatever device is rendering it.
This link, chock full of javascript should help determine which mobile browser is running.

Resources