454 Stimmen

Wie kann ich mit C# eine REST-API aufrufen?

Dies ist der Code, den ich bis jetzt habe:

    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);
            }

        }
    }

Das Problem ist, dass ich denke, dass der Ausnahmeblock ausgelöst wird (denn wenn ich die try-catch entfernen, erhalte ich eine Server-Fehlermeldung (500). Aber ich sehe nicht die Console.Out-Zeilen, die ich in den catch-Block gesetzt habe.

Meine Konsole:

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).

2voto

MNF Punkte 659

Ich habe es auf diese einfache Weise gemacht, mit Web API 2.0. Sie können UseDefaultCredentials entfernen. Ich habe es für meine eigenen Anwendungsfälle verwendet.

List<YourObject> listObjects = new List<YourObject>();

string response = "";
using (var client = new WebClient() { UseDefaultCredentials = true })
{
     response = client.DownloadString(apiUrl);
}

listObjects = JsonConvert.DeserializeObject<List<YourObject>>(response);
return listObjects;

1voto

Denis Punkte 11330

Wir haben begonnen, Speakeasy zu verwenden. Es ist großartig:

https://github.com/jonnii/SpeakEasy

// create a client
var client = HttpClient.Create("http://example.com/api");

// get some companies!
var companies = client.Get("companies").OnOk().As<List<Company>>();

// upload a company, with validation error support
client.Post(company, "companies")
    .On(HttpStatusCode.BadRequest, (List<ValidationError> errors) => {
        Console.WriteLine("Ruh Roh, you have {0} validation errors", errors.Count());
    })
    .On(HttpStatusCode.Created, () => Console.WriteLine("Holy moly you win!"));

// update a company
client.Put(company, "company/:id", new { id = "awesome-sauce" })
    .OnOk(() => Console.WriteLine("Company updated"));

// run a search
client.Get("images/:category", new { category = "cats", breed = "omg the cutest", size = "kittens" })
    .OnOk().As<List<Image>>();

// make an asynchronous request
var response = await client.GetAsync("companies/:id", new { id = 5 })
response.OnOk(UpdateCompaniesCallback)

1voto

Christian Findlay Punkte 5653

Die hier markierte Antwort schlägt vor, den HttpClient direkt zu verwenden und ihn zu entsorgen. Das könnte funktionieren, aber es ist ziemlich einfach, den auf Probleme stoßen mit HttpClient, wenn Sie es nicht richtig verwenden.

Wenn Sie HttpClient verwenden möchten, sollten Sie die Erstellung/Entsorgung von HttpClients besser einer Drittanbieterbibliothek überlassen, die die Fabrikmuster . RestClient.Net ist eine solche Bibliothek.

Es kommt mit einem sehr einfachen HttpClient Fabrik, so dass Sie nicht in die Socket-Erschöpfung Problem laufen,

public class DefaultHttpClientFactory : IHttpClientFactory, IDisposable
{
    #region Fields
    private bool disposed;
    private readonly ConcurrentDictionary<string, Lazy<HttpClient>> _httpClients;
    private readonly Func<string, Lazy<HttpClient>> _createClientFunc;
    #endregion

    #region Constructor
    public DefaultHttpClientFactory() : this(null)
    {
    }

    public DefaultHttpClientFactory(Func<string, Lazy<HttpClient>> createClientFunc)
    {
        _createClientFunc = createClientFunc;
        _httpClients = new ConcurrentDictionary<string, Lazy<HttpClient>>();

        if (_createClientFunc != null) return;
        _createClientFunc = name =>
        {
            return new Lazy<HttpClient>(() => new HttpClient(), LazyThreadSafetyMode.ExecutionAndPublication);
        };
    }
    #endregion

    #region Implementation
    public HttpClient CreateClient(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException(nameof(name));
        }

        return _httpClients.GetOrAdd(name, _createClientFunc).Value;
    }

    public void Dispose()
    {
        if (disposed) return;
        disposed = true;

        foreach (var name in _httpClients.Keys)
        {
            _httpClients[name].Value.Dispose();
        }
    }
    #endregion
}

Aber auch Microsofts IHttpClientFactory-Implementierung kann für das Neueste und Beste verwendet werden:

    var serviceCollection = new ServiceCollection();
    var baseUri = new Uri("http://www.test.com");
    serviceCollection.AddSingleton(typeof(ISerializationAdapter), typeof(NewtonsoftSerializationAdapter));
    serviceCollection.AddSingleton(typeof(ILogger), typeof(ConsoleLogger));
    serviceCollection.AddSingleton(typeof(IClient), typeof(Client));
    serviceCollection.AddDependencyInjectionMapping();
    serviceCollection.AddTransient<TestHandler>();

    //Make sure the HttpClient is named the same as the Rest Client
    serviceCollection.AddSingleton<IClient>(x => new Client(name: clientName, httpClientFactory: x.GetRequiredService<IHttpClientFactory>()));
    serviceCollection.AddHttpClient(clientName, (c) => { c.BaseAddress = baseUri; })
        .AddHttpMessageHandler<TestHandler>();

    var serviceProvider = serviceCollection.BuildServiceProvider();
    var client = serviceProvider.GetService<IClient>();
    await client.GetAsync<object>();

RestClient.Net berücksichtigt die Injektion von Abhängigkeiten und Mocking, IoC Container, Unit-Testbarkeit und vor allem schnell ist. Ich habe herumgejagt und der einzige andere Client, der in einer ähnlichen Kapazität zu arbeiten scheint, ist Flurl.Http.

1voto

rajendra lenka Punkte 19
    var TakingRequset = WebRequest.Create("http://xxx.acv.com/MethodName/Get");
    TakingRequset.Method = "POST";
    TakingRequset.ContentType = "text/xml;charset=utf-8";
    TakingRequset.PreAuthenticate = true;

    //---Serving Request path query
     var PAQ = TakingRequset.RequestUri.PathAndQuery;

    //---creating your xml as per the host reqirement
    string xmlroot=@"<root><childnodes>passing parameters</childnodes></root>";
    string xmlroot2=@"<root><childnodes>passing parameters</childnodes></root>";

    //---Adding Headers as requested by host 
    xmlroot2 = (xmlroot2 + "XXX---");
    //---Adding Headers Value as requested by host 
  //  var RequestheaderVales = Method(xmlroot2);

    WebProxy proxy = new WebProxy("XXXXX-----llll", 8080);
    proxy.Credentials = new NetworkCredential("XXX---uuuu", "XXX----", "XXXX----");
    System.Net.WebRequest.DefaultWebProxy = proxy;

    // Adding The Request into Headers
    TakingRequset.Headers.Add("xxx", "Any Request Variable ");
    TakingRequset.Headers.Add("xxx", "Any Request Variable");

    byte[] byteData = Encoding.UTF8.GetBytes(xmlroot);
    TakingRequset.ContentLength = byteData.Length;

    using (Stream postStream = TakingRequset.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
        postStream.Close();
    }

    StreamReader stredr = new StreamReader(TakingRequset.GetResponse().GetResponseStream());
    string response = stredr.ReadToEnd();

0voto

Dev-lop-er Punkte 338

HTTP GET-Anfrage

    string api = this.configuration["getApiUrl"];//Read from Iconfiguration object injected
     public async Task<HttpResponseMessage> GetAsync(string api, ILogger log, params dynamic[] parameters)
            {
                log.LogInformation($"Get Token");
                var token = await GetTokenAsync(this.configuration["ClientId"], this.configuration["AppKey"]).ConfigureAwait(false);
                using (var client = new HttpClient())
                {
                  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BearerTokenName, token);
                    var apiBaseUrl = this.configuration["BaseUrl"];

                    client.BaseAddress = new Uri(apiBaseUrl);
                    var apiUrl = ConstructUrl(api, parameters);
                    var result = await client.GetAsync(apiUrl).ConfigureAwait(false);

                    if (result.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        return result;
                    }
                    else
                    {
                       throw new HttpResponseException(new HttpResponseMessage(result.StatusCode) { Content = new StringContent(result.ReasonPhrase) });
                    }
                }
            }
  • Lesen Sie String aus HttpResponseMessage wie unten

     var client = await this.httpClientService.GetAsync(url, logger, Convert.ToInt32(Id, CultureInfo.InvariantCulture)).ConfigureAwait(false);
     var response = await client.Content.ReadAsStringAsync();

HTTP POST-Anfrage

     public async Task<string> PostAsync(string api, string contentValue, ILogger logger)
           {
               var token = await GetTokenAsync(this.configuration["ClientId"], this.configuration["AppKey"]).ConfigureAwait(false);

               using (var client = new HttpClient())
               {
                   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BearerTokenName, token);
                   client.BaseAddress = new Uri(resource);
                   var content = new StringContent(contentValue, Encoding.UTF8, MediaTypeNames.Application.Json);
                   var result = await client.PostAsync(new Uri(api, UriKind.Relative), content).ConfigureAwait(false);

                   if (result.StatusCode == System.Net.HttpStatusCode.OK)
                   {
                       return await result.Content.ReadAsStringAsync();
                   }
                   else
                   {
                       throw new HttpResponseException(new HttpResponseMessage(result.StatusCode) { Content = new StringContent(result.ReasonPhrase) });
                   }
               }
           }

    var response = await this.httpClientService.PostAsync(this.configuration["getDetails"], content, this.configuration["ApiBaseUrl"], logger).ConfigureAwait(false);
      catch (System.Web.Http.HttpResponseException httpException)
                        {
                            if (httpException.Response.StatusCode == HttpStatusCode.Unauthorized)
                            {
                                logger.LogError($"Failed To Update", httpException);
                            }
                            else
                            {
                                throw;
                            }
                        }
    return response;

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X