Partager via


How to: Set Headers in the Client Request (WCF Data Services)

Important

WCF Data Services has been deprecated and will no longer be available for download from the Microsoft Download Center. WCF Data Services supported earlier versions of the Microsoft OData (V1-V3) protocol only and has not been under active development. OData V1-V3 has been superseded by OData V4, which is an industry standard published by OASIS and ratified by ISO. OData V4 is supported through the OData V4 compliant core libraries available at Microsoft.OData.Core. Support documentation is available at OData.Net, and the OData V4 service libraries are available at Microsoft.AspNetCore.OData.

RESTier is the successor to WCF Data Services. RESTier helps you bootstrap a standardized, queryable, HTTP-based REST interface in minutes. Like WCF Data Services before it, Restier provides simple and straightforward ways to shape queries and intercept submissions before and after they hit the database. And like Web API + OData, you still have the flexibility to add your own custom queries and actions with techniques you're already familiar with.

When you use the WCF Data Services client library to access a data service that supports the Open Data Protocol (OData), the client library automatically sets the required HTTP headers in request messages sent to the data service. However, the client library does not know to set message headers that are required in certain cases, such as when the data service requires claims-based authentication or cookies. For more information, see Securing WCF Data Services. In these cases, you must manually set message headers in the request message before it is sent. The example in this topic shows how to handle the SendingRequest event to add a new header to the request message before it is sent to the data service.

The example in this topic uses the Northwind sample data service and autogenerated client data service classes. This service and the client data classes are created when you complete the WCF Data Services quickstart. You can also use the Northwind sample data service that is published on the OData Web site; this sample data service is read-only and attempting to save changes returns an error. The sample data services on the OData website allow anonymous authentication.

Example

The following example registers a handler for the SendingRequest event and then executes a query against the data service.

Note

When a data service requires you to manually set the message header for every request, consider registering the handler for the SendingRequest event by overriding the OnContextCreated partial method in the entity container that represents the data service, which in this case is NorthwindEntities.

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Register to handle the SendingRequest event.
// Note: If this must be done for every request to the data service, consider
// registering for this event by overriding the OnContextCreated partial method in
// the entity container, in this case NorthwindEntities.
context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);

// Define a query for orders with a Freight value greater than 30.
var query = from cust in context.Customers
    where cust.Country == "Germany"
    select cust;

try
{
    // Enumerate to execute the query.
    foreach (Customer cust in query)
    {
        Console.WriteLine("Name: {0}\nAddress:\n{1}\n{2}, {3}",
            cust.CompanyName, cust.Address, cust.City, cust.Region);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}
' Create the DataServiceContext using the service URI.
Dim context As NorthwindEntities = New NorthwindEntities(svcUri)

' Register to handle the SendingRequest event.
' Note: If this must be done for every request to the data service, consider
' registering for this event by overriding the OnContextCreated partial method in 
' the entity container, in this case NorthwindEntities. 
AddHandler context.SendingRequest, AddressOf OnSendingRequest

' Define a query for orders with a Freight value greater than 30.
Dim query = From cust In context.Customers _
            Where cust.Country = "Germany" _
            Select cust

Try
    ' Enumerate to execute the query.
    For Each cust As Customer In query
        Console.WriteLine("Name: {0}" & vbNewLine & "Address:" & vbNewLine & "{1}" _
                          & vbNewLine & "{2}, {3}", _
            cust.CompanyName, cust.Address, cust.City, cust.Region)
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
        "An error occurred during query execution.", ex)
End Try

Example

The following method handles the SendingRequest event and adds an Authentication header to the request.

private static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
    // Add an Authorization header that contains an OAuth WRAP access token to the request.
    e.RequestHeaders.Add("Authorization", "WRAP access_token=\"123456789\"");
}
Private Shared Sub OnSendingRequest(ByVal sender As Object, ByVal e As SendingRequestEventArgs)
    ' Add an Authorization header that contains an OAuth WRAP access token to the request.
    e.RequestHeaders.Add("Authorization", "WRAP access_token=""123456789""")
End Sub

See also