Black Tambourine (Posts tagged Web API)

1.5M ratings
277k ratings

See, that’s what the app is perfect for.

Sounds perfect Wahhhh, I don’t wanna

Angular JS and Web API Part 2: Anti-Forgery

Typically you only want to add Anti-Forgery tokens to POST requests for Authenticated users as a security measure. Here’s the steps to get this going:

On your ASP.NET webpage (e.g. a .master file) add the following code to insert a input field for the Antiforgery token:

It’s important to note that MVC and Web API both have their own implementation of AntiForgery, so make sure you have the right DLL referenced and the Import namespace specified above.

Here is an Attribute you can add to your Web API endpoints to handle the token passed in:

Now to pass the token from Angular JS you need to add the following to the request headers of your $resource powered request.

‘post’: { method: 'POST’, headers: { 'X-XSRF-Token’: angular.element('input[name=“__RequestVerificationToken”]’).attr('value’) } }

I’ve simplified this by using a boolen parameter to specify whether to add this, see the services.js in Part 1.

Web API Angular JS anti-forgery

Angular JS and Web API Part 1: ngResource

The ngResource library of Angular has a lot of great functionality to make working with Web API web service quick and easy.

Topics covered in Part 1 of this guide are:

- using $resource to automap endpoint methods, parameters and results to Angular variables/methods.
- leveraging caching for GET methods.
- Error handling async calls to your service.
- working with CRUD methods.

1) Automapping Service Endpoints

Using an Angular factory in combination with $resource we can automap the Web API endpoints. Everything can be automapped except for HttpPut methods which have to be explicitly defined. See here for more info creating crud app in minutes

For each Web API controller we add an Angular factory:

corpServices.factory(‘EventListingService’, newService(’/api/EventListing/:id’, { id: ’@id’ }, true, false));

Here we are passing in the name of the factory to be used in Angular, the url to the service, and the default parameter called id. I’ve put together a 'newService’ function that streamlines things like Anti-forgery tokens and Angular caching.

Here is the services.js file:

2) Caching GET methods with Angular JS

Angular JS has a caching mechanism where if you are calling the same GET service (with the same parameters) multiple times from different places in your code. Rather than send a request to the service multiple times, Angular will call it only once but reuse the result. e.g. A page could have a Navigation service that is shared between the Mega Menu, Breadcrumbs, and side menu. All three controls have a function to get the data from the Service, but Angular will send only send a single network request. All three functions will return the response data from that request.

To set this you need to add a cache parameter against the GET method:

$resource(serviceRoute, parameterObj, {'get’: { method: 'GET’, cache: true }});

I’ve streamlined this with a boolean parameter in the Factory declaration:

corpServices.factory('EventListingService’, newService(’/api/EventListing/:id’, { id: ’@id’ }, true, false));
(see the services.js above).

3) Async calls to your service and error handling

Here is the base.js file, this is a controller that your other controllers can inherit from (i.e. share the functions across).

To inherit from it use Angular Extend within your controllers initialisation:

angular.extend(this, $controller('BaseCtrl’, { $scope: $scope }));

The $scope.callWebApiService() function uses Angular’s $q functionality to create a Promise object to handle the async call. We also have some error handling functions, each result object returned has a property called HasResponseErrors.

Below is an example controller that inherits from the Base and calls a GET service to return data.

Call $scope.callWebApiService() and pass in the name of the service (which we defined in services.js), an object containing your parameters, the function to call on a successfull callback, and the function to call on error.



You can use the .then() functionality of $resource to chain service calls, or alternatively make concurrent async calls.

4) Parameter Automapping

The parameters object can be a complex one with multiple paramaters
e.g. These parameters are automapped to your parameters in your Web API service provided you use [FromUri] for GET method parameters and [FromBody] for POST. In this example i have a Search Request class object with fields for each of the parameters i passed in from Angular:

public IHttpActionResult Get([FromUri]SearchRequest request)

5) CRUD

Here is a more detailed guide that i found helpful: creating crud app in minutes

Here is a quick example of how to do a POST: Here is an example Web API Controller for CRUD scenarios:
Web API Angular JS ngResource