banner



How To Get Address Of Wcf Service

This tutorial shows how to call a web API from a .NET application, using HttpClient .

In this tutorial, we will write an app that consumes the following spider web API.

Action HTTP method Relative URI
Get a product by ID GET /api/products/id
Create a new product Mail /api/products
Update a product PUT /api/products/id
Delete a product DELETE /api/products/id

To learn how to implement this API on the server, using ASP.NET Web API, see Creating a Spider web API that Supports CRUD Operations.

For simplicity, the client application in this tutorial is a Windows panel application.HttpClient is also supported for Windows Telephone and Windows Shop apps. For more information, see Writing Web API Customer Code for Multiple Platforms Using Portable Libraries

Create the Console Application

Start Visual Studio and selectNew Project from theStart page. Or, from theFile menu, selectNew and thenProjection.

In theTemplates pane, selectInstalled Templates and expand theVisual C# node. UnderVisual C#, selectWindows. In the list of projection templates, selectConsole Awarding. Name the project and clickOK.

Install the Web API Client Libraries

Use NuGet Package Director to install the Spider web API Client Libraries package.

From theTools bill of fare, selectLibrary Packet Managing director, so selectPackage Director Console. In the Package Manager Console window, type the following control:

          Install          -          Packet                              Microsoft          .          AspNet          .          WebApi          .          Customer        

Add together the Model Class

Add the following form to the application:

          class                              Production                              {                              public                              cord                              Name                              {                              get          ;                              set          ;                              }                              public                              double                              Price                              {                              get          ;                              set          ;                              }                              public                              cord                              Category                              {                              get          ;                              set          ;                              }                              }        

This class matches the information model used in the "ProductStore" Spider web API project.

Create and Initialize HttpClient

          using                              System          ;                              using                              System          .          Net          .          Http          ;                              using                              Organisation          .          Net          .          Http          .          Headers          ;                              using                              System          .          Threading          .          Tasks          ;                              namespace                              ProductStoreClient                              {                              class                              Program                              {                              static                              void                              Master          ()                              {                              RunAsync          ().          Wait          ();                              }                              static                      async                    Chore                              RunAsync          ()                              {                              using                              (          var                      client                    =                              new                              HttpClient          ())                              {                              // TODO - Send HTTP requests                              }                              }                              }                              }        

Notice that the Chief function calls an async method namedRunAsync and and then blocks untilRunAsyncc completes. Many of theHttpClient methods are async, because they perform network I/O. In theRunAsync method, I'll show the right fashion to invoke those methods asynchronously. It's OK to block the main thread in a console application, but in a GUI application, you should never cake the UI thread.

Theusing argument creates anHttpClient instance and disposes it when the instance goes out of scope. Inside the using statement, add together the following code:

          using                              (          var                      client                    =                              new                              HttpClient          ())                              {                              // New lawmaking:                      client          .          BaseAddress                              =                              new                              Uri          (          "http://localhost:9000/"          );                      client          .          DefaultRequestHeaders          .          Take          .          Clear          ();                      client          .          DefaultRequestHeaders          .          Take          .          Add          (          new                              MediaTypeWithQualityHeaderValue          (          "awarding/json"          ));                              }        

This lawmaking sets the base URI for HTTP requests, and sets the Take header to "application/json", which tells the server to send information in JSON format.

Getting a Resource (HTTP Get)

The following code sends a GET request for a product:

          using                              (          var                      client                    =                              new                              HttpClient          ())                              {                      client          .          BaseAddress                              =                              new                              Uri          (          "http://localhost:9000/"          );                      client          .          DefaultRequestHeaders          .          Have          .          Articulate          ();                      client          .          DefaultRequestHeaders          .          Accept          .          Add          (          new                              MediaTypeWithQualityHeaderValue          (          "application/json"          ));                              // New code:                              HttpResponseMessage                      response                    =                      await client          .          GetAsync          (          "api/products/1"          );                              if                              (          response          .          IsSuccessStatusCode          )                              {                              Production                      production                    =                      await response          .          Content          .          ReadAsAsync          >          Product          >();                              Console          .          WriteLine          (          "{0}\t${1}\t{2}"          ,                      production          .          Name          ,                      product          .          Price          ,                      product          .          Category          );                              }                              }        

TheGetAsync method sends the HTTP GET request. The method is asynchronous, because it performs network I/O. Theawait keyword suspends execution until the asynchronous method completes. When the method completes, it returns anHttpResponseMessage that contains the HTTP response.

If the condition code in the response is a success code, the response body contains the JSON representation of a product. Phone callReadAsAsync to deserialize the JSON payload to aProduct instance. TheReadAsync method is asynchronous considering the response body can be arbitrarily big.

A notation about mistake handling:HttpClient does not throw an exception when the HTTP response contains an error code. Instead, theIsSuccessStatusCode property isfake if the status is an error code.

If you prefer to treat HTTP fault codes as exceptions, call theEnsureSuccessStatusCode method. This method throws an exception if the response status is not a success lawmaking:

          try                              {                              HttpResponseMessage                      response                    =                      await customer          .          GetAsync          (          "api/products/one"          );                      resp          .          EnsureSuccessStatusCode          ()          ;                              // Throw if non a success lawmaking.                              // ...                              }                              catch                              (          HttpRequestException                      e          )                              {                              // Handle exception.                              }        

HttpClient can can throw exceptions for other reasons every bit well — for case, if the request times out.

Using Media-Type Formatters in ReadAsync

WhenReadAsAsync is chosen with no parameters, the method uses the default set of media-blazon formatters to read the response body. The default formatters support JSON, XML, and Form-url-encoded information.

You can also specify a list of formatters, which is useful if you have a custom media-type formatter:

          var                      formatters                    =                              new                              Listing          <          MediaTypeFormatter          >()                              {                              new                              MyCustomFormatter          (),                              new                              JsonMediaTypeFormatter          (),                              new                              XmlMediaTypeFormatter          ()                              };                      resp          .          Content          .          ReadAsAsync          <          IEnumerable          <          Production          >>(          formatters          );        

Creating a Resource (HTTP Postal service)

The following lawmaking sends a Mail service request that contains aProduct example in JSON format:

          // HTTP Mail                              var                      gizmo                    =                              new                              Production          ()                              {                              Name                              =                              "Gizmo"          ,                              Price                              =                              100          ,                              Category                              =                              "Widget"                              };                      response                    =                      await customer          .          PostAsJsonAsync          (          "api/products"          ,                      gizmo          );                              if                              (          response          .          IsSuccessStatusCode          )                              {                              // Become the URI of the created resource.                              Uri                      gizmoUrl                    =                      response          .          Headers          .          Location          ;                              }        

ThePostAsJsonAsync method serializes an object to JSON so sends the JSON payload in a POST request. To send XML, employ thePostAsXmlAsync method. To apply another formatter, callPostAsync:

          MediaTypeFormatter                      formatter                    =                              new                              MyCustomFormatter          ();                      response                    =                      await client          .          PostAsync          (          "api/products"          ,                      gizmo          ,                      formatter          );        

Updating a Resource (HTTP PUT)

The post-obit lawmaking sends a PUT asking to update a product.

          // HTTP PUT                      gizmo          .          Toll                              =                              eighty          ;                              // Update price                      response                    =                      await client          .          PutAsJsonAsync          (          gizmoUrl          ,                      gizmo          );        

ThePutAsJsonAsync method works likePostAsJsonAsync, except that it sends a PUT request instead of POST.

Deleting a Resources (HTTP DELETE)

The following lawmaking sends a DELETE request to delete a product.

          // HTTP DELETE                      response                    =                      expect client          .          DeleteAsync          (          gizmoUrl          );        

Similar GET, a DELETE request does non accept a request body, so you don't need to specify JSON or XML format.

Complete Lawmaking Example

Here is the complete code for this tutorial. The code is very simple and doesn't testify error handling, but it shows the basic CRUD operations usingHttpClient.

          using                              System          ;                              using                              System          .          Net          .          Http          ;                              using                              System          .          Cyberspace          .          Http          .          Headers          ;                              using                              System          .          Threading          .          Tasks          ;                              namespace                              ProductStoreClient                              {                              form                              Production                              {                              public                              string                              Name                              {                              get          ;                              set          ;                              }                              public                              double                              Price                              {                              get          ;                              set          ;                              }                              public                              string                              Category                              {                              become          ;                              set          ;                              }                              }                              course                              Program                              {                              static                              void                              Main          ()                              {                              RunAsync          ().          Wait          ();                              }                              static                      async                    Task                              RunAsync          ()                              {                              using                              (          var                      client                    =                              new                              HttpClient          ())                              {                      client          .          BaseAddress                              =                              new                              Uri          (          "http://localhost:9000/"          );                      client          .          DefaultRequestHeaders          .          Accept          .          Clear          ();                      customer          .          DefaultRequestHeaders          .          Accept          .          Add          (          new                              MediaTypeWithQualityHeaderValue          (          "application/json"          ));                              // HTTP GET                              HttpResponseMessage                      response                    =                      await client          .          GetAsync          (          "api/products/i"          );                              if                              (          response          .          IsSuccessStatusCode          )                              {                              Production                      product                    =                      await response          .          Content          .          ReadAsAsync          <          Product          >();                              Console          .          WriteLine          (          "{0}\t${one}\t{two}"          ,                      product          .          Name          ,                      product          .          Price          ,                      product          .          Category          );                              }                              // HTTP Mail service                              var                      gizmo                    =                              new                              Product          ()                              {                              Proper noun                              =                              "Gizmo"          ,                              Price                              =                              100          ,                              Category                              =                              "Widget"                              };                      response                    =                      await client          .          PostAsJsonAsync          (          "api/products"          ,                      gizmo          );                              if                              (          response          .          IsSuccessStatusCode          )                              {                              Uri                      gizmoUrl                    =                      response          .          Headers          .          Location          ;                              // HTTP PUT                      gizmo          .          Price                              =                              80          ;                              // Update price                      response                    =                      await client          .          PutAsJsonAsync          (          gizmoUrl          ,                      gizmo          );                              // HTTP DELETE                      response                    =                      await client          .          DeleteAsync          (          gizmoUrl          );                              }                              }                              }                              }                              }        

How To Get Address Of Wcf Service,

Source: https://sites.google.com/site/wcfpandu/web-api/calling-a-web-api-from-c-and-calling-a-web-api-from-view

Posted by: lachancegera1975.blogspot.com

0 Response to "How To Get Address Of Wcf Service"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel