共用方式為


How to: Make Requests to HTTP-Based Services

Microsoft Silverlight will reach end of support after October 2021. Learn more.

HTTP-based services return data when an HTTP request is sent to a particular URI.

HTTP requests can be sent to a variety of URIs. Examples of such URIs include:

The HTTP request is usually configured with the GET verb, which implies retrieval, or the POST verb, which implies invocation. The service being accessed might require parameters to be sent with the request. For HTTP GET, parameters are usually appended to the end of the URI: https://fabrikam.com/service/getUser?id=123. For HTTP POST, parameters are part of the body of the HTTP request.

The data the service returns is contained in the HTTP response. The format of the data depends on the service implementation. Common data formats returned by HTTP-based services include XML, JSON, or RSS/Atom. The format of the data and its schema (except in the case of RSS/Atom, which have standard schemas) are usually described by the developer of the service in human-readable documentation.

Silverlight version 4 provides two methods for sending HTTP requests: WebClient and HttpWebRequest. When choosing which of these methods to use in a Silverlight client application to retrieve data from an HTTP-based Web service, consider the following differences that generally make WebClient the simpler option:

  • Method invocations from Silverlight clients must be asynchronous, but HttpWebRequest has an asynchronous programming model using delegates, whereas WebClient uses an event-based asynchronous programming model. The event-based model is simpler to use and generally requires fewer lines of code.

  • HttpWebRequest supports a larger subset of the HTTP protocol, which tends to make it more appropriate for some advanced scenarios because it offers more control over service requests.

  • The WebClient callback, which is raised when the HTTP response is returned, is invoked on the User Interface (UI) thread, and can be used to update the properties of UI elements. It can, for example, be used to display the data in the HTTP response. The HttpWebRequest callback, by comparison, is not returned on the UI thread, so extra code is needed to work with the UI from that callback. This tends to make WebClient a better fit for applications that need to update the UI.

This topic outlines how to use the WebClient option for obtaining data form an HTTP-based Web service.

By default, all HTTP calls in Silverlight 4 are handled by the Web browser networking stack. There are some limitations in the browser networking stack that can interfere with the access to REST-based services. To work around these limitations, Silverlight 4 offers an alternative networking stack, which is based on the client operating system. That stack offers a different set of capabilities that may be better suited to accessing REST-based services. The list includes:

  • The full complement of the HTTP methods, not just GET and POST

  • HTTP response status codes

  • HTTP headers and bodies

  • Other HTTP features

For more information about client HTTP handling, see How to: Specify Browser or Client HTTP Handling.

To call an HTTP-based Web service

  1. (Optional) In Silverlight 4, the browser provides HTTP handling of Web requests and responses for your applications by default. To opt into client HTTP handling of requests and responses for the given service instead, register the correct prefix by specifying ClientHttp for the networking stack.

    WebRequest.RegisterPrefix("https://fabrikam.com/service", WebRequestCreator.ClientHttp);
    

    (The conditions under which client HTTP handling is more appropriate for accessing REST-based services were discussed above.)

  2. Create the URI to which the request is sent. This URI can point to static data, for example an RSS/Atom feed stored in a file /data.xml.

    Uri serviceUri = new Uri("https://fabrikam.com/service/getUser"); 
    
    Cc197953.security(en-us,VS.95).gif Security Note:
    Note that if this service is hosted on a different domain than the Silverlight control, the service must opt in to cross-domain access if it is to be accessible to the control. For more information, see Making a Service Available Across Domain Boundaries.
  3. Create a WebClient instance to make the HTTP GET request and download the response.

    WebClient downloader = new WebClient();
    
  4. Because WebClient only supports asynchronous requests, register a callback to call when the request is completed and make the request to the specified URI.

    downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
    downloader.OpenReadAsync(serviceUri);
    
  5. Define the downloader_OpenReadCompleted event handler to get the HTTP response. Be sure to check the value of the Error property to ensure that it is null and no errors were encountered while making the HTTP request.

    void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        if (e.Error == null)
        {
    
        }
    }
    
  6. Inside the if statement, get an Stream object that contains the response.

    Stream responseStream = e.Result;
    
  7. Depending on the type of data contained in the response, continue with one of the procedures described in Working with XML Data, Working with JSON Data, or Working with RSS or Atom Feeds.

Example

You should now have the following code.


public void HowToMakeRequestsToHttpBasedServices()
{
    Uri serviceUri = new Uri("https://fabrikam.com/service/getUser");
    WebClient downloader = new WebClient();
    downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
    downloader.OpenReadAsync(serviceUri);
}

void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Error == null)
    {
        Stream responseStream = e.Result;

        // Continue working with responseStream here...
    }
}

See Also

Send comments about this topic to Microsoft.

Copyright © 2010 by Microsoft Corporation. All rights reserved.