SORU
8 Mart 2012, PERŞEMBE


Nasıl arama bir REST apı c kullanarak yaptığım#?

Bu şimdiye kadar sahip olduğum kodu:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
using System.Web;
using System.Net;
using System.IO;

namespace ConsoleProgram
{
    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json?api_key=123";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)
        {
            Class1.CreateObject();
        }

        private static void CreateObject()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json"; 
            request.ContentLength = DATA.Length;
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
            requestWriter.Write(DATA);
            requestWriter.Close();

             try {
                WebResponse webResponse = request.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                Console.Out.WriteLine(response);
                responseReader.Close();
            } catch (Exception e) {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }
    }
}

Sorun özel durum bloğu (çünkü ben bir server ben try-catch, hata (500) mesajı kaldırın. tetiklenir olduğunu düşünüyorum Ama Konsol görmüyorum.Kesik catch bloğu koydum.

Benim Konsol

The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0).
The thread '<No Name>' (0x1988) has exited with code 0 (0x0).
The thread 'vshost.LoadReference' (0x1710) has exited with code 0 (0x0).
'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', Symbols loaded.
'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
A first chance exception of type 'System.Net.WebException' occurred in System.dll
The thread 'vshost.RunParkingWindow' (0x184c) has exited with code 0 (0x0).
The thread '<No Name>' (0x1810) has exited with code 0 (0x0).
The program '[2780] ConsoleApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

Visual Studio 2011 Beta kullanıyorum .NET 4.5 Beta.

CEVAP
3 Temmuz 2013, ÇARŞAMBA


ASP.NET Web API, XML Web API daha önce de belirttiğim yerini aldı.

Ben dedim post güncelleştirilmiş bir cevap beri en çok bu tepkiler erken 2012 ve bu konuyu bir üst sonuçlar ne zaman bir Google arama yapmak için "arama dinlendirici hizmeti c#".

Microsoft geçerli rehberlik API İstemci Kitaplıkları Microsoft ASP.NET Web Dinlendirici bir hizmetini kullanmak için kullanmaktır. Bu NuGet paketi, Microsoft olarak kullanılabilir.AspNet.WebApi.İstemci.

Örnek ASP.NET Web API İstemci Kitaplığı kullanılarak uygulanan gibi görünür:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleProgram
{
    public class DataObject
    {
        public string Name { get; set; }
    }

    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json";
        private string urlParameters = "?api_key=123";

        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;
                foreach (var d in dataObjects)
                {
                    Console.WriteLine("{0}", d.Name);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }  
        }
    }
}

Daha fazla ayrıntı, diğer örnekler de dahil olmak üzere, buraya gidin: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

Faydalı olabilir de bu blog yazısı: http://johnnycode.com/2012/02/23/consuming-your-own-asp-net-web-api-rest-service/

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • AutoStream's Garage419

    AutoStream's

    15 EKİM 2007
  • Max Lee

    Max Lee

    18 AĞUSTOS 2006
  • Numberphile

    Numberphile

    15 EYLÜL 2011