How can I write an MVC3 / 4 application that can function as a web API and user interface for this API?

My title is very well suited for this. My first, although it is to provide several data formats, one of which is HTML, which I can provide and consume using the Razor viewer and the actions of the MVC3 controller respectively. It is then possible to provide other data formats through custom browsing mechanisms. I have never worked in this area before, except for very simple web services, a very long time ago. What are my options? What is this web interface API that I see related to MVC4?

NOTE My main HTML application should not work directly with the API. I would like to write an API first, guided by the requirements of a skeletal HTML client, with a very rudimentary user interface, and after the API is complex, then write a fully functional UI client using the same services as the API, but bypassing the actual analysis components API data and views.

+7
source share
9 answers

I had the same thought as soon as the first conversation about the web API was around. In short, the Web API is a new product from MS.NET Web Stack that is built on top of WCF, OData, and MVC to provide a single way to create a RESTful Web API. A lot of resources on this, so you have Google.

Now to the question ..

The problem is that you can of course force the web API to return HTML, JSON, XML, etc., but the missing part here are the views / templates provided by Razor / ASPX / insertviewenginehere. This is not really the work of the "API".

Of course, you could write client-side code to call your web API and run the templating / UI client program with the massive number of plugins available.

I am sure that the web API is not capable of returning template HTML in the same way as the ASP.NET MVC web application can do.

Therefore, if you want to "reuse" certain parts of your application (repository, domain, etc.), it would be best to wrap the calls in the facade / services style and make both your web API and a separate web application ASP.NET MVC to reduce code.

All you need to do is an ASP.NET MVC web application that calls your domain and creates template HTML, and an ASP.NET Web API application that calls your domain and returns various resources (JSON, XML, etc. ).).

If you have a well-structured application, then this form of abstraction should not be a problem.

+8
source

I suggest developing the application in such a way that you use one controller to return the original application resources (html, javascript, etc.) to the browser. Build your API / logic in WebAPI endpoint services and access these services through JavaScript. Essentially creating a one-page application. Using MVC 4, our controller can return different types depending on the device (phone, desktop, tablet), but using the same JavaScript, all your clients will be able to access the service.

Good search libraries include KnockoutJS , SammyJS, or BackBoneJS

+2
source

If you have a requirement to return HTML using WebAPI, for example. so that users can click around and explore your API using the same URL, then you can use the \ html routing 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 complete example, check: - https://github.com/arble/WebApiContrib.MessageHandlers.Html

+1
source

I played with this idea before. I showed the API via MVC3 as JSONResult methods on different controllers. I have implemented custom security for the API using controller action filters. Then the heavy AJAX HTML interface was built, which used JSON services. It worked quite well and had excellent performance, since all the data transferred for the web application was through AJAX.

+1
source

Here you need to read on MVC and the web API - Using HTTP, your application is your API .

+1
source

Frederick Normen has a good position in Using Razor with the ASP.NET Web API: http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net- web-api.aspx

One important limitation of a well-designed REST service is the use of "hypermedia as an application state mechanism" (HATEOAS - http://en.wikipedia.org/wiki/HATEOAS ).

It seems to me that HTML is a great choice to support as one of the media formats. This will allow developers and other users to view and interact with your service without a specially created client. This, in turn, can lead to faster customer development for your service. (When it comes to developing real HTML clients, it would be wiser to use json or xml.) It would also force the development team into a more efficient recreation service, as you would have to structure your views in such a way that makes it easier for end users to navigate with using a browser.

I think it would be wise for any development team to take a similar approach to Frederick’s example and create a media type format that generates an HTML interface for a leisure service based on reflection on the return type and using conventions (or what it’s kind of similar - given the reflection, I would like to make sure that the html media format was used only for research by developers. Perhaps you will make it available only in certain environments.).

I am sure that in the end I will do something like this (if someone else has not done this or if there is not any other function in the web api that does this. I am a little new to the Web API), Maybe it will my first NuGet package. :) If so, I will post here when it is done.

+1
source

Have you seen this video ? You can download it before viewing, so it does not skip.

0
source

Creating Html is the job for the Mvc controller, not Web Api, so if you need something that can return both jSon and Html generated using some kind of viewing mechanism, the best option is the standard Mosc Controller Action methosd. Consolidation of content, that is, the format for the return, can be achieved using Action Fiter. I have an action filter that allows the controller to receive "prompts" from the client in the returned format. The client may ask to return a view with a specific name or jSon. The hint is sent either in the query line or in a hidden field (in case the request comes from the submit form). Code 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); } } 
0
source

Now, after some time through the beta, MS has just released the candidate version MVC4 / VS2012 / etc. Speaking on the navigation / help pages (mentioned by some other posters), they added a new class, IApiExplorer. I managed to put together a self-documenting help page that automatically collects all of my ApiControllers and uses the comments that I already set to document them.

My architectural recommendation, as others have said, would be to divert your application to something like “MVCS” (Model, View, Controller, Services), which you may know as something else. What I did was separate my models in a separate class library, and then split my services into another library. From there, I use dependency injection with Ninject / Ninject MVC3 to catch my implementations as needed and just use the interfaces to capture the data I need. As soon as I have the data (which, of course, is represented by my models), I do everything I need to set it up for presentation and send it to the client.

Starting with MVC3, I have one project that I ported to MVC4 that uses “traditional” Razor markup, etc., and a new project that will be a one-page AJAX application using Backbone + Marionette and some other things. so far this experience has been really great, it is very easy to use. I found some good Backbone + Marionette guides here, although they can be a little confusing and require a little digging in the documentation to put it all together, simply as soon as you hang it:

Basic input at Backbone.js: http://arturadib.com/hello-backbonejs/docs/1.html

Use cases for Marionette views (I found this useful when deciding to create views for my complex models): https://github.com/derickbailey/backbone.marionette/wiki/Use-cases-for-the-different-views

0
source

All Articles