by Richard Seroter offers an industry-leading set of web service APIs that developers can use to interact with their cloud applications. The Microsoft .NET framework is widely used to build custom applications, and it also forms the foundational layer of Microsoft products such as Microsoft SharePoint. Developers have many reasons to integrate their .NET applications with data and business logic. This article walks through the techniques and best practices for consuming SOAP and REST services in .NET 4.5 applications. Integration Services

Developers can access to a wide range of integration points exposed by the platform. These includes:

  • SOAP API. SOAP has been the standard web service protocol for over a decade. SOAP messages are in XML format and are typically sent over HTTP. Many existing commercial products natively support SOAP and the SOAP description file – called a WSDL – makes it easy to generate proxy objects for custom .NET applications. The SOAP API gives developers access to all out-of-the-box and custom APEX objects in their organization.
  • REST API. The Representational State Transfer (REST) service style is quickly becoming the preferred way to create and consume web services. REST services embraces the architecture of the web and relies on defining representations of resources that are typically transmitted via XML or JSON over HTTP using a standard interface (e.g. GET, POST, PUT, DELETE). provides a rich RESTful API that makes it easy for developers to interact with all the objects in their organization.
  • Bulk API. The Bulk API is designed to efficiently load large data sets into a organization. The API works with both XML and CSV records, and leverages parallel servers on the platform to speed up processing.
  • Streaming API. Like the Bulk API, the Streaming API processes data asynchronously. It lets applications connect to a near real-time stream of data out of and provides a viable alternate to the query technique offered by the SOAP and REST APIs.

While this article focuses on using the out-of-the-box SOAP and REST APIs, all of these APIs – including custom Apex SOAP and Apex REST APIs – give .NET developers ample ways to interact with the platform.


.NET Web Service Technologies

Microsoft offers a range of technologies for creating and consuming web services. These include:

  • ASP.NET XML Web Services. This is the original SOAP web services technology from Microsoft. It’s known for its limited – but simple – framework for creating web services. Developers can consume existing SOAP services with the ASP.NET XML Web Services framework by creating “Web References” within Visual Studio.
  • Windows Communication Foundation (WCF). A comprehensive framework for building SOAP and REST web services. It supports a full set of WS* standards for building sophisticated applications. It makes heavy use of configuration files and has numerous extensibility points. While primarily targeted at SOAP services, WCF later added limited support for creating RESTful services. Developers can use WCF proxies to consume existing SOAP services by creating “Service References” within Visual Studio.
  • ASP.NET Web API. A modern set of libraries for building REST services on the .NET framework (version 4.5 and above). It lets developers easily create web APIs that can consume and return XML or JSON messages.
  • HttpClient. A new base object included in .NET 4.5 that makes it simpler to call HTTP services. It has a collection of asynchronous service operations that developers use to send HTTP requests to web endpoints.

In general, Microsoft recommends using WCF for calling and creating SOAP services, the ASP.NET Web API for creating RESTful services, and the HTTPClient for calling web endpoints.


Creating a SOAP Service Reference

To start off with, consume the SOAP API from within Visual Studio 2012. One of the benefits of SOAP web services is that they have a WSDL that can be used to generate strongly-typed proxy objects. It works best to download a copy of the WSDL (instead of pointing to the online version), so navigate to the API page and save a copy of the Enterprise WSDL to your local hard drive.


After the WSDL file is saved locally, create a Visual Studio 2012 project and add a new Service Reference to the project by right-clicking the project and selecting Add Service Reference. Point to the Enterprise WSDL on your local hard drive and notice that the full set of operations are available. In this example, the service reference is named SfdcReference. This name is used throughout the project to refer to the objects included in the Enterprise API proxy.


Notice that after the service reference is added, a new entry is added to the project’s configuration file. The endpoint XML node holds the “ABCs” (address, binding, and contract) of the WCF proxy used to call the service. The web service address included in the Enterprise API points to<version>. When the developer calls the login operation, they get back the web service URL to use for all the subsequent API operations.


This project’s WCF service reference can be used over and over again in the .NET project and gives the developer a strongly-typed set of objects to work with.


Authenticating SOAP Users

Consumers of the Enterprise API must authenticate themselves before accessing the data and functionality in Once a security token is acquired, it is included in all subsequent API calls. The security token is associated with a single user account and all the access permissions associated with that account. For example, if a user is allowed to view Account records but cannot create them, then the same permission policy will apply if that user attempts to call the “create” API operation against the Account object. To read more about and the API security model, see the article entitled Security and the API in the developer documentation.

Also, don’t forget to make sure that the user record you plan to use with the API is actually enabled for API access. The user should be associated with a Profile that has API Enabled selected.


In the Visual Studio project, add the necessary using statement (with alias) to reference the Enterprise API types.

Next, add the necessary code to invoke the Login operation using the user name, password, and security token of the API-enabled user account. In the code below, notice that the developer is not exposed to the raw HTTP communication with when using the WCF proxy components. Consider wrapping the call to the Login operation in a try-catch block to capture any exceptions that are thrown by the login attempt.

Assuming that the login operation succeeds, the resulting payload contains both the session ID and the API service endpoint URL. Note that the session expires after two hours of inactivity (by default), and every time the API is called, the session inactivity timer is reset to 0.


Querying and Creating Objects Via SOAP Enterprise API

With a valid session in hand, it’s time to interact with records through the API. Queries are executed in using the Salesforce Object Query Language (SOQL). This language bears a striking resemblance to traditional SQL queries and should be easy for developers to pick up. The results of the Query operation are stored in a QueryResult object and developers have access to a cursor reference (for large result sets), the returned records, and a size property that contains the count of records returned from the query.

In the code below, notice that the SessionHeader object is created and loaded with the session ID acquired from the Login operation. When using the WCF proxy object (instead of the legacy ASP.NET XML Web Services proxy object), there are many more parameters included in the Query operation. They are all useful, but the only required parameter is the SOQL query string.

The records property in the QueryResult object contains an array of base SObjects. Since the SOQL query calls for Account objects to be returned, the results can be cast to the Account type for easier access to object properties. In the case below, the results are cast using the IEnumerable.Cast<TResult> method, which doesn’t actually cast the object until it’s accessed by the enumerator.

Refer to SOAP Headers for more information about the SOAP headers used in this section's code samples.

At this point, you’ve successfully issued a secure query against using WCF proxy objects. What if you know exactly which record(s) you want returned? You can issue a SOQL query that returns a single record or records, or, a better option is to use the Retrieve operation. This applies to records that are all of the same object type and the developer has control over which object fields to return.

In the code below, notice that the Retrieve operation takes in an array of record IDs. This operation returns an array of SObjects that can be cast do the corresponding object type for easier access.

Querying is useful, but the Enterprise API supports much more than that. The Enterprise API supports a full set of operations, including query, retrieve, search, create, upsert, update, merge, delete, and much more. This next example walks through the steps to create a new record via the Enterprise API.

The Enterprise API provides us with strongly-typed objects for every out-of-the-box and custom object in your organization. The Create operation inserts objects (of different types, if you so desire) into the database. Below, see that an instance of the Account type is instantiated and populated with values. Be aware that an extra Boolean field is generated for each non-string field and if you do not set this value to "true,” then the corresponding field value won’t be sent to For example, the Account object below has a field called AnnualReview that is of .NET data type “double.” Therefore, there is an additional field added to the strongly-typed Account object named AnnualReviewSpecified. For each non-string field that is set in an object, this additional field must be set as well or it won’t be included in the outbound SOAP message.

The result of the Create operation is stored in an array of SaveResult objects which contain the newly minted ID value for record, and success or failure indicators.

That’s all there is to it! You’ve now created a record in using the Enterprise API. The strong object typing makes development simpler, but comes at a cost. If the objects change in any way (e.g. new or deleted object fields, altered data types), then the Enterprise WSDL must get refreshed and your code might have to change. If you need more flexibility and adaptability to change, consider the Partner API.

Querying and Creating Objects Via Partner API

The Partner API, as its name suggests, is primarily targeted at partners who build applications to be consumed by many organizations. They cannot afford to tightly couple to any one organization’s schema and need a more dynamic model to work with. The Partner API relies on a set of name-value pairs that are more forgiving and adaptable to change. The WSDL for the Partner API is downloaded from the same place as the Enterprise WSDL, and only needs to be referenced a single time by the consuming application. Notice below that when you add a Service Reference to the Partner WSDL, you can see the same set of API operations as what exists in the Enterprise WSDL.


After adding a WCF Service Reference to the Partner WSDL within your .NET project, notice that the corresponding application configuration file receives a new endpoint node that has the same URL address, but a different contract.


When calling the Partner API, your code will initially look very similar to the code for calling the Enterprise API. There are still strongly typed objects for interacting with the service endpoint, but the only difference is that none of the data objects are available. The developer works only with the base sObject type instead of concrete types like Account or Contact. Before jumping into the code that queries the database through the Partner API, add the necessary using statement (with alias) to the code.

The code below uses the same SOQL query as with the example above, but the code itself diverges from the Enterprise API example once the results of the query are returned. Instead of an sObject that can be cast to a strongly typed data object, the Partner API returns an sObject with an array of XmlElements that contain the object’s data. To access the object data, you can choose to use either of the two methods demonstrated below. Notice that the “acctName” variable is populated by pulling the XmlElement at the first index array. However, this is a bit brittle as it will break if the query is rewritten and the fields come back in a different order. An alternate approach uses LINQ to grab the XmlElement with a “name” attribute matching the field name. This approach has no dependency on field ordering and is a bit easier to read.

Refer to SOAP Headers for more information about the SOAP headers used in this section's code samples.

You have now successfully queried using the more flexible Partner API. As you saw, accessing object properties isn’t as straightforward as when you use the strongly-typed Enterprise API, but the Partner API makes it easier to build applications that can span organizations and tolerate change.

Much like the Enterprise API, the Partner API supports all the various CRUD (create-read-update-delete) operations on an object. In the code below, a new Account record is created in the database. There are a number of key things to be aware of when calling this API operation from .NET code. First, notice that you must create an array of XmlElements to hold all of the field values. An XmlElement object cannot be explicitly instantiated via the “new” keyword, and must be created from an underlying XmlDocument object. Note that you can choose to use the LINQ-friendly XElement class to build up the array of fields, but then you’d be responsible for converting that array to the XmlElement type in order to be compatible with the WCF proxy objects.

Once the array of XElements is populated with each desired field, the array is attached to the “Any” property of the sObject that is sent across the wire to Observe that the Create operation accepts a wide range of optional parameters that control how the system behaves when accepting and processing the new record. Finally, like with the Enterprise API, the results of the operation are loaded into a SaveResult object array that can then be inspected to determine whether the operation succeeded or failed.

Now you’ve added a new record to your organization through the Partner API.

The SOAP APIs are a great choice when you have a development environment like Visual Studio that can consume a WSDL and provide a strongly-typed set of classes to work with. SOAP is also a good fit for relatively static organizations that don’t undergo a lot of changes to object definitions. You also saw that the WCF proxy for the SOAP APIs has operations that accept a wide range of (optional) headers that give you expansive control over the behavior of the system.

However, there are also great reasons to embrace the REST API, even when using Microsoft .NET and Visual Studio. REST is friendlier to mobile clients because of its lightweight message size and choice of either XML or JSON for data format. RESTful services also don’t enforce schemas that have to be updated every time the data model changes.

Next up, let’s look at how to consume the REST API from a .NET client application.

Authenticating REST Users

Much like the SOAP APIs offered by, the REST API requires users to be authenticated before accessing the data or functionality within the organization. While it is possible to reuse the SOAP-based authentication token for REST service calls, a better option is to embrace one of the OAuth 2.0 authentication flows. In the scenario below, you will use the username-password OAuth authentication flow to pass credentials to and acquire a valid session token.

Before writing any code, the first thing to do is establish Remote Access for the client application. This permits the client application to use OAuth for user authentication. Access these settings on the management portal by visiting Setup –> Develop –> Remote Access. Create a new entry by providing a unique application name, contact email, and a callback URL. Be aware that the callback URL is for browser-based scenarios where the application user is redirected after the authentication succeeds. In this case, the callback URL value is not used.


With the remote access configured, you’re now ready to authenticate with the REST endpoint. These examples use the new HttpClient class found in the .NET Framework 4.5. As mentioned at the beginning of this article, the HttpClient class provides operations for invoking web APIs. These operations run asynchronously so you have the chance to take advantage of the new Async and Await keywords present in .NET 4.5.

First, create variables to hold the various values needed to authenticate to the service. In reality, it makes the most sense to retrieve these values from a (secure) repository and NOT hardcode them into your client application. In order to authenticate against the OAuth endpoint, you need five values: Consumer Key and Consumer Secret (both from the Remote Access entry), and the username, password, and security token. Next, the message to the OAuth endpoint must be URL encoded and include the grant_type ( password + security token), client_id (Consumer Key), client_secret (Consumer Secret), username ( username), and password ( password).

If the credentials are valid, the OAuth endpoint returns a JSON payload containing the issue date, instance URL, signature, and access token. In the code below, notice that you save off the instance URL and token for later use.

You have now authenticated a .NET client application against the REST endpoint. The resulting security token will be used next as you query and create objects in the database through the REST API.

Querying and Creating Objects Via REST API

The REST API offers a variety of ways to query the database. You can use the URL to pull back all records for a specific object, execute an SOQL query, perform searches, or retrieve a single record by ID. In each case, you can choose whether should return that data in XML or JSON format. In the example below, you will perform an SOQL query similar to the queries that were executed with the SOAP API above.

First, define a new HttpClient object. Next, author the SOQL query. Notice below that there are examples of other queries that can be executed against the REST API. To have control over the outbound headers, instantiate an HttpRequestMessage, set the HTTP operation to GET, add the URL with the SOQL query, and add the OAuth token to the “Authorization” header. Next, choose the data format of the records returned from Both “application/xml” and “application/json” are valid values. Finally, call the SendAsync operation and process for the response.

The HttpClient is a useful library for interacting with REST services and saves the user from all the stream interactions that were necessary when working with the HttpWebRequest object in the past.

Next, create a new Account record through the REST API. First, create a new HttpClient object. Next, define the payload of the new Account. The REST API accepts either XML or JSON payloads. JSON payloads are formulated by creating name-value pairs of each field that you want added to the object. If you want to send an XML message, start with a node called “root” and create elements that match the name of the object fields.

Create an HttpRequestMessage and set the HTTP method to POST. This is the HTTP verb used when creating new records. Next, craft the URL so that it points to the object type of the new record. In this case, “/sobjects/Account.” Once again add the OAuth token to the header so that the request can be authorized. Call the SendAsync operation and see that the response string contains the ID of the newly created record.

Congratulations! You just queried and created records in via the REST API.


The family of APIs provide comprehensive access to all the business logic and data in a application. The SOAP and REST APIs give developers a powerful interface for real-time integration with Visual Studio and .NET make it easy to consume web services from any provider. In this article we saw how to reference the SOAP API, establish a secure session, query records, and create records using both the strongly-typed Enterprise API and the flexible Partner API. For mobile clients or applications that don’t need the capabilities or heft of SOAP services, the REST API is a great choice. We saw how developers can quickly and easily authenticate to the OAuth endpoint, query records, and create brand new ones.

Newer versions of the .NET framework offer capabilities like LINQ, REST support, and asynchronous programming, but even if you’re using an older version of .NET, you can still readily consume all the SOAP and REST APIs.

About the Author

Richard Seroter is a product manager for cloud computing provider Tier 3, a Microsoft MVP, Pluralsight trainer, speaker, and author of multiple books on application integration strategies. Richard maintains a regularly updated blog on topics of architecture and solution design and can be found on Twitter as @rseroter.


Integrating with the Platform

Integrating with Microsoft .NET

API Implementation Considerations

Getting Started with the REST API