Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs
Contact   •   Articles   •   Products   •   Support   •   Search
Ad-free experience sponsored by:
ASPOSE - the market leader of .NET and Java APIs for file formats – natively work with DOCX, XLSX, PPT, PDF, images and more

Where does ASP.NET Web API Fit?


With the pending release of ASP.NET MVC 4 and the new ASP.NET Web API, there has been a lot of discussion of where the new Web API technology fits in the ASP.NET Web stack. There are a lot of choices to build HTTP based applications available now on the stack - we've come a long way from when WebForms and Http Handlers/Modules where the only real options. Today we have WebForms, MVC, ASP.NET Web Pages, ASP.NET AJAX, WCF REST and now Web API as well as the core ASP.NET runtime to choose to build HTTP content with.

Web API definitely squarely addresses the 'API' aspect - building consumable services - rather than HTML content, but even to that end there are a lot of choices you have today. So where does Web API fit, and when doesn't it?

But before we get into that discussion, let's talk about what a Web API is and why we should care.

What's a Web API?

HTTP 'APIs' (Microsoft's new terminology for a service I guess)  are becoming increasingly more important with the rise of the many devices in use today. Most mobile devices like phones and tablets run Apps that are using data retrieved from the Web over HTTP. Desktop applications are also moving in this direction with more and more online content and synching moving into even traditional desktop applications. The pending Windows 8 release promises an app like platform for both the desktop and other devices, that also emphasizes consuming data from the Cloud.

Likewise many Web browser hosted applications these days are relying on rich client functionality to create and manipulate the browser user interface, using AJAX rather than server generated HTML data to load up the user interface with data.

These mobile or rich Web applications use their HTTP connection to return data rather than HTML markup in the form of JSON or XML typically. But an API can also serve other kinds of data, like images or other binary files, or even text data and HTML (although that's less common). A Web API is what feeds rich applications with data.

ASP.NET Web API aims to service this particular segment of Web development by providing easy semantics to route and handle incoming requests and an easy to use platform to serve HTTP data in just about any content format you choose to create and serve from the server.

But .NET already has various HTTP Platforms

The .NET stack already includes a number of technologies that provide the ability to create HTTP service back ends, and it has done so since the very beginnings of the .NET platform. From raw HTTP Handlers and Modules in the core ASP.NET runtime, to high level platforms like ASP.NET MVC, Web Forms, ASP.NET AJAX and the WCF REST engine (which technically is not ASP.NET, but can integrate with it), you've always been able to handle just about any kind of HTTP request and response with ASP.NET. The beauty of the raw ASP.NET platform is that it provides you everything you need to build just about any type of HTTP application you can dream up from low level APIs/custom engines to high level HTML generation engine. ASP.NET as a core platform clearly has stood the test of time 10+ years later and all other frameworks like Web API are built on top of this ASP.NET core.

However, although it's possible to create Web APIs / Services using any of the existing out of box .NET technologies, none of them have been a really nice fit for building arbitrary HTTP based APIs. Sure, you can use an HttpHandler to create just about anything, but you have to build a lot of plumbing to build something more complex like a comprehensive API that serves a variety of requests, handles multiple output formats and can easily pass data up to the server in a variety of ways. Likewise you can use ASP.NET MVC to handle routing and creating content in various formats fairly easily, but it doesn't provide a great way to automatically negotiate content types and serve various content formats directly (it's possible to do with some plumbing code of your own but not built in). Prior to Web API, Microsoft's main push for HTTP services has been WCF REST, which was always an awkward technology that had a severe personality conflict, not being clear on whether it wanted to be part of WCF or purely a separate technology. In the end it didn't do either WCF compatibility or WCF agnostic pure HTTP operation very well, which made for a very developer-unfriendly environment.

Personally I didn't like any of the implementations at the time, so much so that I ended up building my own HTTP service engine (as part of the West Wind Web Toolkit), as have a few other third party tools that provided much better integration and ease of use. With the release of Web API for the first time I feel that I can finally use the tools in the box and not have to worry about creating and maintaining my own toolkit as Web API addresses just about all the features I implemented on my own and much more.

ASP.NET Web API provides a better HTTP Experience

ASP.NET Web API differentiates itself from the previous Microsoft in-box HTTP service solutions in that it was built from the ground up around the HTTP protocol and its messaging semantics. Unlike WCF REST or ASP.NET AJAX with ASMX, it’s a brand new platform rather than bolted on technology that is supposed to work in the context of an existing framework. The strength of the new ASP.NET Web API is that it combines the best features of the platforms that came before it, to provide a comprehensive and very usable HTTP platform. Because it's based on ASP.NET and borrows a lot of concepts from ASP.NET MVC, Web API should be immediately familiar and comfortable to most ASP.NET developers.

Here are some of the features that Web API provides that I like:

  • Strong Support for URL Routing to produce clean URLs using familiar MVC style routing semantics
  • Content Negotiation based on Accept headers for request and response serialization
  • Support for a host of supported output formats including JSON, XML, ATOM
  • Strong default support for REST semantics but they are optional
  • Easily extensible Formatter support to add new input/output types
  • Deep support for more advanced HTTP features via HttpResponseMessage and HttpRequestMessage
    classes and strongly typed Enums to describe many HTTP operations
  • Convention based design that drives you into doing the right thing for HTTP Services
  • Very extensible, based on MVC like extensibility model of Formatters and Filters
  • Self-hostable in non-Web applications 
  • Testable using testing concepts similar to MVC

Web API is meant to handle any kind of HTTP input and produce output and status codes using the full spectrum of HTTP functionality available in a straight forward and flexible manner.

Looking at the list above you can see that a lot of functionality is very similar to ASP.NET MVC, so many ASP.NET developers should feel quite comfortable with the concepts of Web API. The Routing and core infrastructure of Web API are very similar to how MVC works providing many of the benefits of MVC, but with focus on HTTP access and manipulation in Controller methods rather than HTML generation in MVC.

There’s much improved support for content negotiation based on HTTP Accept headers with the framework capable of detecting automatically what content the client is sending and requesting and serving the appropriate data format in return. This seems like such a little and obvious thing, but it's really important. Today's service backends often are used by multiple clients/applications and being able to choose the right data format for what fits best for the client is very important.

While previous solutions were able to accomplish this using a variety of mixed features of WCF and ASP.NET, Web API combines all this functionality into a single robust server side HTTP framework that intrinsically understands the HTTP semantics and subtly drives you in the right direction for most operations. And when you need to customize or do something that is not built in, there are lots of hooks and overrides for most behaviors, and even many low level hook points that allow you to plug in custom functionality with relatively little effort.

No Brainers for Web API

There are a few scenarios that are a slam dunk for Web API. If your primary focus of an application or even a part of an application is some sort of API then Web API makes great sense.

HTTP Services
If you're building a comprehensive HTTP API that is to be consumed over the Web, Web API is a perfect fit. You can isolate the logic in Web API and build your application as a service breaking out the logic into controllers as needed. Because the primary interface is the service there's no confusion of what should go where (MVC or API). Perfect fit.

Primary AJAX Backends
If you're building rich client Web applications that are relying heavily on AJAX callbacks to serve its data, Web API is also a slam dunk. Again because much if not most of the business logic will probably end up in your Web API service logic, there's no confusion over where logic should go and there's no duplication. In Single Page Applications (SPA), typically there's very little HTML based logic served other than bringing up a shell UI and then filling the data from the server with AJAX which means the business logic required for data retrieval and data acceptance and validation too lives in the Web API. Perfect fit.

Generic HTTP Endpoints
Another good fit are generic HTTP endpoints that to serve data or handle 'utility' type functionality in typical Web applications. If you need to implement an image server, or an upload handler in the past I'd implement that as an HTTP handler. With Web API you now have a well defined place where you can implement these types of generic 'services' in a location that can easily add endpoints (via Controller methods) or separated out as more full featured APIs. Granted this could be done with MVC as well, but Web API seems a clearer and more well defined place to store generic application services. This is one thing I used to do a lot of in my own libraries and Web API addresses this nicely. Great fit.

Mixed HTML and AJAX Applications: Not a clear Choice 

For all the commonality that Web API and MVC share they are fundamentally different platforms that are independent of each other. A lot of people have asked when does it make sense to use MVC vs. Web API when you're dealing with typical Web application that creates HTML and also uses AJAX functionality for rich functionality. While it's easy to say that all 'service'/AJAX logic should go into a Web API and all HTML related generation into MVC, that can often result in a lot of code duplication. Also MVC supports JSON and XML result data fairly easily as well so there's some confusion where that 'trigger point' is of when you should switch to Web API vs. just implementing functionality as part of MVC controllers.

Ultimately there's a tradeoff between isolation of functionality and duplication. A good rule of thumb I think works is that if a large chunk of the application's functionality serves data Web API is a good choice, but if you have a couple of small AJAX requests to serve data to a grid or autocomplete box it'd be overkill to separate out that logic into a separate Web API controller. Web API does add overhead to your application (it's yet another framework that sits on top of core ASP.NET) so it should be worth it

.Keep in mind that MVC can generate HTML and JSON/XML and just about any other content easily and that functionality is not going away, so just because you Web API is there it doesn't mean you have to use it. Web API is not a full replacement for MVC obviously either since there's not the same level of support to feed HTML from Web API controllers (although you can host a RazorEngine easily enough if you really want to go that route) so if you're HTML is part of your API or application in general MVC is still a better choice either alone or in combination with Web API.

I suspect (and hope) that in the future Web API's functionality will merge even closer with MVC so that you might even be able to mix functionality of both into single Controllers so that you don't have to make any trade offs, but at the moment that's not the case.

Some Issues To think about

Web API is similar to MVC but not the Same

Although Web API looks a lot like MVC it's not the same and some common functionality of MVC behaves differently in Web API. For example, the way single POST variables are handled is different than MVC and doesn't lend itself particularly well to some AJAX scenarios with POST data.

Code Duplication

I already touched on this in the Mixed HTML and Web API section, but if you build an MVC application that also exposes a Web API it's quite likely that you end up duplicating a bunch of code and - potentially - infrastructure. You may have to create authentication logic both for an HTML application and for the Web API which might need something different altogether. More often than not though the same logic is used, and there's no easy way to share. If you implement an MVC ActionFilter and you want that same functionality in your Web API you'll end up creating the filter twice.

AJAX Data or AJAX HTML

On a recent post's comments, David made some really good points regarding the commonality of MVC and Web API's and its place. One comment that caught my eye was a little more generic, regarding data services vs. HTML services. David says:

I see a lot of merit in the combination of Knockout.js, client side templates and view models, calling Web API for a responsive UI, but sometimes late at night that still leaves me wondering why I would no longer be using some of the nice tooling and features that have evolved in MVC ;-)

You know what - I can totally relate to that. On the last Web based mobile app I worked on, we decided to serve HTML partials to the client via AJAX for many (but not all!) things, rather than sending down raw data to inject into the DOM on the client via templating or direct manipulation. While there are definitely more bytes on the wire, with this, the overhead ended up being actually fairly small if you keep the 'data' requests small and atomic. Performance was often made up by the lack of client side rendering of HTML.

Server rendered HTML for AJAX templating gives so much better infrastructure support without having to screw around with 20 mismatched client libraries. Especially with MVC and partials it's pretty easy to break out your HTML logic into very small, atomic chunks, so it's actually easy to create small rendering islands that can be used via composition on the server, or via AJAX calls to small, tight partials that return HTML to the client. Although this is often frowned upon as to 'heavy', it worked really well in terms of developer effort as well as providing surprisingly good performance on devices. There's still plenty of jQuery and AJAX logic happening on the client but it's more manageable in small doses rather than trying to do the entire UI composition with JavaScript and/or 'not-quite-there-yet' template engines that are very difficult to debug. This is not an issue directly related to Web API of course, but something to think about especially for AJAX or SPA style applications.

Summary

Web API is a great new addition to the ASP.NET platform and it addresses a serious need for consolidation of a lot of half-baked HTTP service API technologies that came before it. Web API feels 'right', and hits the right combination of usability and flexibility at least for me and it's a good fit for true API scenarios. However, just because a new platform is available it doesn't meant that other tools or tech that came before it should be discarded or even upgraded to the new platform. There's nothing wrong with continuing to use MVC controller methods to handle API tasks if that's what your app is running now - there's very little to be gained by upgrading to Web API just because. But going forward Web API clearly is the way to go, when building HTTP data interfaces and it's good to see that Microsoft got this one right - it was sorely needed!

Resources


I'll be at DevIntersection in Vegas this fall giving sessions on ASP.NET Core with Angular and Localization. Thinking of coming? Use discount code STRAHL and save a few bucks. If you do be sure to stop by and say hello!

ASP.NET DevIntersection 2017. Rick Strahl Coupon Code

Posted in Web Api  

The Voices of Reason


 

mattmc3
August 07, 2012

# re: Where does ASP.NET Web API Fit?

It feels like Web API is an answer to Ruby's Sinatra (and the .NET version, Nancy https://github.com/thecodejunkie/Nancy). In fact, I'm not sure what compelling story Nancy will have with Web API in the picture. It seems like a great fit for small apps where you want a light backend and have a very rich Javascript-y client-side experience with something like knockout. And as SPAs take off, and NoSQL databases where the resulting data is JSON, Web API gives the perfect, light data front-end for quick-and-dirty AJAX calls for raw data. Also, and this is the biggest win I see, it gives us back the simple simple .asmx WebMethods use-case that WCF stole. Anything that eats into the ugly bloated config-heavy beast that is WCF is a huge win in my book. After falling for Ruby's Sinatra, I'm really looking forward to using Web APIs for my .NET work.

Joe Wilson
August 07, 2012

# re: Where does ASP.NET Web API Fit?

Nice post! I have been trying to tease apart MVC and the Web API, and this helps.

BTW, you have a bad link for the text "David made some really good points". It goes to localhost.

John Papa
August 07, 2012

# re: Where does ASP.NET Web API Fit?

Nice post. There's often a balance that we must strike when creating web apps. It is important to understand that here may not be a black and white answer. Your post does a great job of laying out the pros and cons of the choices. The bottom line is it DOES depend on your situation and your goals and your team's dev skills.

Web API is great for serving JSON data to the modern SPA type client. But there is nothing wrong with sending html to that type of client either (as you point out). 3 good are:
1) solve the business problem
2) provide good user experience (includes performance and perceived performance)
3) make it maintainable

I think we're at a good starting point for Web API.

Glenn Block
August 08, 2012

# re: Where does ASP.NET Web API Fit?

Nice post Rick!

Definitely agree that it is not a black and white decision. I would say use the thing that is easiest for the problem you are trying to solve.

If you are building out a full fledged API to be consumed by different devices / native apps or even a combination then I think you'll find yourself in places where Web API will just be easier.

In other cases like simply serving up a few JSON endpoints to an browser based frontend where the API is really an implementation detail then there's nothing wrong with JsonResult.

Really like your capturing of the different scenarios / things to think about when choosing web api.

Thanks!

Tomasz Kubacki
August 08, 2012

# re: Where does ASP.NET Web API Fit?

There is better webservice framework than webapi take a look www.servicestack.net

Eric Schoenholzer
August 08, 2012

# re: Where does ASP.NET Web API Fit?

Great article and thoughts. WebAPI is a huge step forward, but after my experiences it isn't made for serving complex data. You need to return simple DTO, and not your complex data model.

Jamie
August 08, 2012

# re: Where does ASP.NET Web API Fit?

Like you I ended up writing my own HTTP service API some time ago. When Web API came out I was hoping to move away from my own code since there a lot of plumbing in there that I would prefer not to maintain, and I'd rather use something standard anyway. But honestly I still find the new model falls short in basic implementation details.

You still need to add an entry to the routing table that perfectly matches the signature of each method when designing a custom API (e.g. not just using standard CRUD/REST methods). Like MVC routes the method parameter name is matched against the route parameter name. Why? Parameter names should be source code details, not something that creates a dependency. The routes should be matched on signature, not on parameter names.

Frankly I see no reason that we should have to create routes AT ALL beyond the minimum pattern required to identify a URL as being a route, e.g. "api/{query}". The framework should be able to match a URL to a method signature. Not doing this creates duplication of code - there is a necessity to create a route for each individual HTTP method you create, when the method signature already defines that explicitly.

This is how I developed my own implementation - it just uses reflection to analyze the C# methods that are identified (via class or method attributes) as HTTP methods, and then generate a route table based on those signatures. There's of course some conventions involved here (e.g. how to identify the data parameter for POST methods, some infrastructure for DI when you have a parameter types that are not instantiable such as interfaces, and so on) but none of it is especially complicated. At the end of the day a method signature (perhaps with a little metdata in an attribute if it's complicated) should be enough to define a route.

I was disappointed to find that Web API did nothing to simplify this, unless I'm missing something. You should be able to just create a method on a class and have it be a functioning route without manually creating a matching signature on the route table too.

Stephen
August 08, 2012

# re: Where does ASP.NET Web API Fit?

Great post Rick.... I've been using a generic handler with Newtonsoft's JSON.Net and it has worked so so well that I'm hesitant to jump ship, but your post definitely sheds some light on some new stuff coming down the pipe

Kris
August 08, 2012

# re: Where does ASP.NET Web API Fit?

Great post Rick.

So why haven't you written a textbook yet?

I'm sure if you wrote books about ASP.NET MVC and/or Web API it would sell quite well.

I sure as heck would buy one.

Anyways, keep up the informative posts as checking out your site is a daily staple of mine (and should be for all .Net developers).

Mel
August 08, 2012

# re: Where does ASP.NET Web API Fit?

Great post. I agree that Web API is good, however it has one extreme flaw: Authentication. (I'm serious. Do a search for "asp.net web api security using Forms Authentication" and no practical example will come up.)

The way that ASP.NET Web API is going, they are steering everyone away from Forms authentication and want to force you to use tokens instead. So now, we have to rethink (again) how to authenticate users using tokens. Can't Web API just adopt to what is the here and now (Forms Authentication)?

So now, for you to use ASP.NET Web API, you have to rethink how to authenticate your users with Web API and at the same time authenticate them with your website instead of forcing them.

Rick Strahl
August 08, 2012

# re: Where does ASP.NET Web API Fit?

@Eric - what exactly do you think doesn't work in your 'complex data' scenarios? Can you be more specific? You'll have to do mapping yes, but beyond that I'm not sure what you'd expect to work differently with 'complex data types'?

@Jamie - Not sure I understand. You don't need to create custom routes for every request. If you don't use Verb based routing then you can use create
'/api/{controller}/{action}' or '/{controller}/{action}/{id}' which sounds pretty much what you're describing for class/method matching no? Maybe you missed that you can provide the controller because most examples don't show that?

@Mel - forms and Windows authentication will work just fine however. If you login either via AJAX or through an HTML interface that login carries through the application into Web API.

In general though, APIs tend to be based around authentication tokens, because if you're not in a browser doing authentication header stuff is not universally supported by HTTP clients. But nothing is preventing you from using standard Web auth especially if you're using an AJAX backend.

Mel
August 08, 2012

# re: Where does ASP.NET Web API Fit?

@Rick,

I tried to use Forms auth with Web API, but it doesn't work. I created two projects - one web api with Sytem.Web.Http.Authorize on all api controllers and one MVC project with Sytem.Web.Mvc.Authorize on all mvc controllers. The login info is stored in the db. What I do is I log myself in the MVC project using forms auth, then I try to access the API using HttpClient class in one of the mvc controllers. I always get HTTP 401 and it does not go past that.

Jamie
August 08, 2012

# re: Where does ASP.NET Web API Fit?

@Rick it's fine if your API only has methods that accept a single parameter called "id", that is, things that just perform a single operation with no parameters on a single record. But outside of basic verb stuff for database operations, there are lots of things (most, even) that can't be described that way. Certainly DB operations are the most common part of an API but any nontrivial application is going to do lots of stuff other than crud operations or simple DB operations that only take an ID parameter.

For example: anything with more than one parameter:

/api/controller/getpage/2/10
public IMyDataStructure GetPage(int startPage, int rows);

/api/settings/set/name/value
public void GetPage(string settingName, string settingValue);

/api/controller/makelabel/view/type2/600
public HttpResponseMessage MakeLabel(DisplayMode mode, LabelType type, int dpi);

.. or organization that has more than one level

/api/section/subsection/dosomething

Unless I am mistaken, each of these methods would require a unique entry in the routing table. It's also annoying that I have to call my ID parameter "ID" (or whatever, but generally, the same thing) on every method in order to be able to use the same route for more than one method. ID is highly un-descriptive and a potential source of bugs if you happen to be handling more than one ID in a given block of code. "somethingId" is much more descriptive.

But regardless of your preference in parameter naming conventions this creates an artificial constraint on how you write your code, for which I can't think of any benefits. Is there some situation where this would disambiguate a route? I can't think of any functionality it adds.

Rick Strahl
August 09, 2012

# re: Where does ASP.NET Web API Fit?

@Mel - if I do the following:

[HttpPost]
public HttpResponseMessage Authenticate(LoginData login)
{
    var username = login.Username;
    var password = login.Password;
 
    bool authenticated = FormsAuthentication.Authenticate(username, password);
    var cookie = FormsAuthentication.GetAuthCookie(username, false);
 
    if (!authenticated)
        return Request.CreateResponse<bool>(HttpStatusCode.Unauthorized, false);
 
    var response = Request.CreateResponse<bool>(HttpStatusCode.OK, true);
    response.Headers.AddCookies(new CookieHeaderValue[1] { new CookieHeaderValue(cookie.Name, cookie.Value) });
 
    return response;
}
 
[HttpGet]
public bool IsAuthenticated()
{
    if (User.Identity.IsAuthenticated)
        return true;
 
    return false;
}


that works just fine, so forms authentication is definitely working on the server and in Web API.

So you say you log in the browser, and then try to call the API with HttpClient() from an MVC controller? This won't work because the server is not logged in - only the browser is. You might be able to get this to work by capturing the auth cookie in your MVC controller and assigning that to the HttpClient(), but that's a hack at best. But why would you ever do that? If you really need that type of capture and forward security in your app then that's exactly what token based security is designed for as you just pass the token forward.

For Forms Auth to work the client needs to send the server generated auth cookies back. The browser handles this automatically, but when you use a standalone HTTP client HTTP cookies need to be captured and forwarded to the next request. Read the cookie when retrieving data, write it when you send to the server.

Note also that Forms Auth only works in IIS. For self-hosting, you need another mechanism which is why the Web API folks recommend a token based approach that doesn't depend on the hosting platform.

Bill Woodruff
August 11, 2012

# re: Where does ASP.NET Web API Fit?

I enjoyed reading this excellently written article, and being someone who was a highly developed WinForms C# programmer, who did not like the first versions of ASP.NET, or the later versions that implemented what to me is an excessively over-engineered, and esoteric, implementation of MVC ... solutions based on which, have high $ overhead once you build to a robust site that can handle high load-demand, in terms of licensing fees for Windows Server, SQL, etc.

Well, I turned my attention to the parlor-maid- (JavaScript) -gone-to-the-ball, as Cinderellla, which became ubiquitious, and to HTML5, Node.js, and other non-MS stack web technologies.

Reading you article, I still have no sense of in what practical real-world scenarios one would adopt Web API:

1. a portfolio site for a antique dealer, low volume, lots of pictures, and galleries ?

2. a high-volume consumer good sales site with e-commerce ?

3. an interactive forum where there are topics, threads, posts, replies to posts, etc. ?

4. a high-security financial market securities trading system with atomic precision regarding timing of automatic trades, and stable, predictable performance over thousands of transactions per day. ?

While this lack of "vision" on my part may be just a reflection of my own lack of understanding, I think it would be interesting, and appreciated, if you would care to write in more detail about exactly the types of real-world web-solutions you choose Web API for.

thanks, Bill Woodruff

Jon
August 22, 2012

# re: Where does ASP.NET Web API Fit?

Hi Rick,

Great post!

Simple question really. I've used your bit of code for returning a cookie from the API but I can't seem to figure out how I use this cookie for accessing another API. How do I send or use the cookie that I have when making an AJAX request to another API (like api/movie/getmovie/1)

The movie api has the [Authorize] attribute so blocks anything until it's authorised. Would be great for some tips on this.

This is a bit of AngularJS I use to get the cookie

            var login = {
                Password: '',
                Username: ''
            };
            $http.post('api/user/authenticate',
                login
            ).success(function (data) {
                //Do something with the cookie
            });


Thanks
Jon

Rick Strahl
August 22, 2012

# re: Where does ASP.NET Web API Fit?

@Jon - are you talking about an HTTP cookie? If so once the cookie is set the browser picks it up and subsequent requests will automatically send the cookie. If you need to pass a token around (ie. you log in and get some ID that identifies the user to pass back to APIs) then you'd need to manage that token and pass it as needed.

Jon
August 23, 2012

# re: Where does ASP.NET Web API Fit?

Hi Rick,

Yes I'm talking about a HTTP cookie. I don't understand how it gets set when it's returned from the API. Do I have to do anything with it to store or is it supposed to be automatic?

Once the cookie is set it should then be sent with every request to the API?

Thanks
Jon

Rick Strahl
August 23, 2012

# re: Where does ASP.NET Web API Fit?

@Jon - it just works. XHR *is* the browser, so an AJAX request picks up the cookie and the browser carries that cookie forward in HTML and AJAX requests after that...

foobar
August 26, 2012

# re: Where does ASP.NET Web API Fit?

This is a decent writeup.

If you have experience of developing in Web API and AngularJs or KnockoutJs, I'd welcome your story on it.

Aykut Ucar
August 27, 2012

# re: Where does ASP.NET Web API Fit?

@Jamie,
Have you seen this?
Maybe it can help.
https://github.com/mccalltd/AttributeRouting
Thanks.

Victor
September 10, 2013

# re: Where does ASP.NET Web API Fit?

Rick,

How would you implement logout? On the client side I suppose you can just delete the cookie (how do you get a handle of it?). Or is it something else? What would you do on the server side? I suppose you call the FormsAuthentication API to logout. Anything else?
A code sample would be great.

Another question I have is how can you create a "clean" web api project? It comes bundled with a bunch of js libraries, mvc controllers, mvc dll references and whatnot. How do I make it clean? I'm thinking if I ever want to self host the thing, I can just switch to token based auth and it should work (maybe also be able to run on mono?).

And one last thing: how do I deal with my "client" website? I want to have a full website written in sencha ext.js (mvc pattern) or kendo ui (mvvm) and use web api to fetch/push data. I currently placed the website in a separate project and I'm hosting the web api project as a sub-site (called api in IIS so that routes can hit my api controllers - I removed the "api" from the defined routes and kept only {controller} so that api will actually map to the webapi website). Should I handle authentication differently there? Will that be ... merged together?

Thanks!
 

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2017