Don't think of ASP.NET as an island. It's a citizen of the larger community. More and more of ASP.NET is open source, and we push hard every day to stay open and be open. We want to make ASP.NET more pluggable, more open, more fun. We've got big things planned - some that will surprise you. I hope you'll join the conversation and the community.

In fact, in the interest of focusing on One ASP.NET, the "WCF Web API" is now ASP.NET Web API and it comes with ASP.NET MVC now. Even though it ships with MVC 4 Beta today, don't let that take away from the One ASP.NET vision. You can use Web API in ASP.NET Web Forms no problem. That's kind of the point. ;)

Why do you want a Web API?

I can use XML or JSON or something else with my API. JSON is nice for mobile apps with slow connections, for example. You can call an API from jQuery and better utilize the client's machine and browser. You can make a Gmail type single page, or a hybrid; it's up to you.

How it all fits into One ASP.NET

The idea behind One ASP.NET is that I want folks to be able to make apps that have real-time components with SignalR, clean, simple APIs with Web API, all in one pages with KnockoutJS, pages with MVC, Web Forms or Web Pages, as well as existing ASP.NET systems like OData, ASMX, and more. I want open source projects like JSON.NET, KnockoutJS, SignalR, Backbone, MongoDB, Scaffolding, NHIbernate, Ninject (and the list goes on) to all play in the same ASP.NET LEGO sandbox. We'll put all these subcomponents on NuGet and they'll live alongside community components and you'll be able to build ASP.NET applications starting from some base template and add just the pieces you want. We are getting there. I want folks to use the parts they want, and swap out the parts they don't. Everything should work together. I've always said I want to open source everything we can as fast as Microsoft can take it, and I'll keep pushing if it kills me my boss.

Here's my Web API controller code. A few things to notice. I'm talking to the same IRepository that the page controller uses. I'm returning HTTP Status Codes that are appropriate for each response. See how after the Create (where I POST a JSON representation of NotATweet) that I return HttpStatusCode.Created 201 and set the header's location to include the location of the new resource?

Then I'll hit /api with Fiddler. Notice how JSON popped out the other end?

I'll change the accept header to Accept: application/xml and xml pops out. You can plug in your own and make Web API spit out iCal or whatever you like. You can make media formatters or even plug in others for the defaults. For example, here's a JSON.NET Formatter for Web API.

Notice that the result is an HTTP 201 Created. If I then GET /api, I can see it's there:

I can also affect things with the URL and query strings like this GET /api?$orderby=Username HTTP/1.1 so I can so query composition without totally buying into OData-style URLs if I don't want to.

As I mentioned, I can use XML or JSON or something else with my API. JSON is good for mobile apps with slow connections, for example. You can call this API from jQuery and better utilize the client's machine and browser.

We've got a new section up on the ASP.NET site http://asp.net/web-api with a lot of info. Here's some resources for easily adding an API to your app. You can even self-host your own Web API without IIS in a service or other application!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

Hi Scott. Any idea how DTO->view model object mapping would fit into this whole flow? For example: I want public IQueryable<NotATweet> Get() to actually return NotATweetViewModel. I could do this manually (via automapper/some custom function) but then I lose the OData filtering provided by the framework and be enumerate the whole IQueryable<>. I've been trying all day to do this via an action filter but I haven't had much success. Ideally I'd love to let the framework do its thing, then have an OnActionExecuted filter handle the transformation.

I've been asking around in the official wep api forums but haven't had much luck. Any insight would be appreciated.. thanks! = )

Annoyingly, I couldn't find a super simple web pages-like JSON API alternative, the closest was using WebClientFactory WCF .svc's, which have their own set of problems. MVC is a nice architecture, but it's crazily overweight for introducing when you are still playing around with code-first TDD against the database, especially when I'm not even serving HTML in the end! Of course, that's a pretty edge case, and I could just write an IHttpHandler subclass, but it seems like a violation of the LEGO-brick concept that JSON APIs depend on the HTML generation machinery at all.

Simon - Can you be more specific? I've done JSON.net and IHttpHandler, Kayak and Owin, using a single .cshtml web page to return JSON, or just return json() from a controller. All are very lightweight. Returning Json() doesn't invoke any HTML building or page generation stuff (views).

Scott Hanselman

Saturday, 25 February 2012 03:24:03 UTC

So then of course, I see that the related links talk about how you can use Web API without MVC extremely simply! Though the http://www.asp.net/web-api should really include that Henrik post, it's example for using WebAPI without MVC is crazily complicated, showing off far to many unrelated features.

Simon - good point! I'll update the site to make it clearer that it is lightweight.

Rob - We are all friends here! ;)

Scott Hanselman

Saturday, 25 February 2012 05:12:03 UTC

Can we hope for something like Kayak in the ASP.NET lego box? We want to do web services between medical devices in a closed network. A lightweight, open source web server from Microsoft would be really nice.

I have read that the PUT and DELETE actions should be idempotent methods, meaning that multiple identical requests should have the same effect as a single request.

Looking at your code does this is not true for the delete method. At least the second call results in an exception thrown. If the entity does not exist even the first call would result in an exception.

Apart from that I am rather keen on the Web API. Thanks for a great post!

Regards Andreas Kroll

Saturday, 25 February 2012 15:45:02 UTC

Installing the Nugets "aspnetwepapi" on my MVC3 app works nicely too :-) LEGO-yes I known - just had to unhook that mvc4 thought..

Scott: yes , we use that already. But we also need to render web pages. The scenario is this: a device measures patient's vital signs. Other devices pull that data via Web API. A nurse walks around with a tablet, where we render that same data in a browser.

We did a prototype using Web API, SignalR and MVC3 and it all worked, but the lack of a lightweight server is a problem. So I'm now running Louis DeJardin's firefly with Nancy and will probably stay with that.

MVC4 looks great. But there is still that big unwieldy lego piece -the server- that steers me away from the entire stack.Having to deal with http.sys , netsh, urlacl, running things as admin. There has to be a better way.

Just when you thought you knew it all!! boom something fantastic and exciting on the Microsoft stack to learn I can already see this keeping me awake at night I think 4.5 is an exciting release great work go team goThanks

The only doubt I have about this is in comparison to *.ws is the descriptional part. With web services it's quite easy to implement the service and send the wsdl to someone else (including the comments) and they will be able to use it.

You are correct that DELETE is an Idempotent operation, but idempotency relates to how the server state is affected. In this case once the resource has been removed and a DELETE is sent you get a 404, which is completely valid as the server state is not effected.

Technically PUT should really compare the state being updated to the state of the resource and if it has not changed then it is no-op. However in this case it is just overwriting itself with the same values so from the client perspective nothing has really change.

OH MY GOD, YES. I loved the WCF Web Api (sic) when it was first trialled on Codeplex. It makes so much sense. However, the URL templating, the ServiceRoute<T> paradigm, it all seemed to fit the ASP.NET (MVC in particular) world so much more.

FYI, I threw together a quick tutorial for making requests using the HttpClient class that's included in the latest bits. It's a rough cut, but it gets it done. Consuming your own ASP.NET Web API REST Service I will try and add the POST and PUT examples soon, and I welcome any feedback!

Monday, 27 February 2012 17:48:42 UTC

Scott,

I am interested in the One ASP.NET concept as it relates to Web API and SignalR. I don't know much about SignalR other that what I read from your post in August. My question is, how are these two services meant to be utilized in one ASP.NET application? What type of requests would each service handle?

Is the WebAPI trying to move the services towards REST? All this looks like WCF REST services, except we are using controller in an MVC application.

So do we need to have 2 controllers? 1 extending from Controller base and another from ApiController base?

Arun Sandeep

Wednesday, 29 February 2012 21:46:45 UTC

how about a vb.net example?

jim

Thursday, 01 March 2012 16:43:37 UTC

Great article, Scott.

Is it true that you're not adding support for OData $select queries for the RTM? Seems kind of a shame if you aren't.

mads

Saturday, 03 March 2012 02:42:59 UTC

It's pretty exciting for me too, when working for the new version for Employee Info Starter Kit, for demonstrating cool stuffs available in ASP.NET MVC & Web API 4.0. Guys you can have a early look at here.

Can the authorize attribute work well with certain clients that will not support cookies authentication? Does it switch to header based authentications when needed? I would love a tutorial or more explanation on using authentication over web api.

Hey Scott, loving the MVC4 beta so far. Any word if we are going to get full OData support in the official release of MVC 4? Specifically the inlinecount option. Not having this really kills the ability to do any kind of paging (efficiently).

Likning.If i use entity framework, using à stored procedure, to gather data; lets say that i get the objekt from class that have id like belowClass myclass{Public int id;}I want to insert à link to the resppnse like below:<myclass> <id>10000</<id><link hef="bablablabla" rel="self"><myclass>

how easy is that??

Thaks in advance

Johan kvist

Saturday, 01 September 2012 11:22:00 UTC

All the examples for web api that I have seen post a single object to the api. Is it possible to post a collection of objects (IQueryable<NotATweet>) to the api and have the nice automatic json to .net conversion happen?

Really though how are we supposed to trust Microsoft ever again as a developer after them abandoning Silverlight and WPF? They are all HTML5 and Javascript now, which are great things but now they are just another open source Javascrip vendor (and not so open)....and the other vendors do a better job....why bother really? Do you really think we are going to jump on the Metro bandwagon and have the rug pulled out from us again? I am dumb but I am not stupid. I remember going to PDC and listening to Doug Purdy yelling about how Oslo was the greatest thing since sliced bread. I could go on and on....Microsoft has lost me and I am sure many others. Off to learn python....

1) Is there a web page somewhere that shows all the options for the Scaffold command line options?2) Is there a way for the scaffold to look at the entity framework for keys and default values without having to modify the entity framework generated code?

Thanks,Michael

Michael Akin

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.