Hallo,
ich möchte eine Json-Abfrage von meinem Client in meinem Server empfangen und eine Json-Antwort zurücksenden. Aber in meinem Client bekomme ich immer > Fehlermeldung:
System.Net.WebException ("Der Remoteserver hat einen Fehler zurückgegeben: (400) Ungültige Anforderung.") vorgeworfen und im Server kommt kein Context. Kann mir hierbei jemand helfen? Danke im voraus.
Client: (JReq ist ein byte[] aus dem Ergebnis von JsonConvert.SerializeObject()
HttpWebRequest WEBRequest = WebRequest.CreateHttp("http://127.0.0.1:50051/");
WEBRequest.Credentials = new NetworkCredential("usr", "pass");
WEBRequest.ContentType = "application/json";
WEBRequest.ContentLength = JReq.Length;
WEBRequest.Method = "POST";
using (var streamWriter = new StreamWriter(WEBRequest.GetRequestStream()))
{
streamWriter.Write(JReq);
streamWriter.Close();
}
HttpWebResponse resp = (HttpWebResponse)WEBRequest.GetResponse(); //Hier bekomme ich die Excaption
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
//Read Resault
}
Server:
private async void Listen()
{
string Prefix = $"http://*:50051/";
HttpListener _listener = new HttpListener();
_listener.Prefixes.Add(Prefix);
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
_listener.Start();
while (true)
{
try
{
Response(await _listener.GetContextAsync());
}
catch (Exception ex)
{
}
}
}
private void Response(HttpListenerContext context)
{
if (context.User.Identity.IsAuthenticated)
{
//Check Login
System.IO.Stream body = context.Request.InputStream;
System.Text.Encoding encoding = context.Request.ContentEncoding;
System.IO.StreamReader sr = new System.IO.StreamReader(body, encoding);
if (context.Request.ContentType != null)
{
string s = sr.ReadToEnd();
try
{
var json = JObject.Parse(s);
//Use Json and write answer
StreamWriter sw = new StreamWriter(context.Response.OutputStream);
sw.Write(JsonConvert.SerializeObject(/*Answer*/));
}
catch
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NoContent;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();
}
Trifft eine Programmiererin ihre Freundin und die Freundin fragt: "Mit welchen Typen hängst du so in letzter Zeit rum?" Die Programmiererin antwortet: „integers, booleans und strings“
HttpListener ist deprecated, seit bald 2 Jahren auch so aktiv kommuniziert. Er unterstützt moderne Protokolle und Verschlüsselungen nicht und bekommt keine Updates mehr.
Er sollte nicht mehr verwendet werden.
Verwende zB ASP.NET Core als Server und Refit als Client.
Und wenn man die Security nicht sicher im Griff hat, dann sollte man sowieso auf Frameworks setzen. Dein Code sieht hier insgesamt sehr sehr abenteuerlich aus 😉
- performance is a feature -
Microsoft MVP - @Website - @AzureStuttgart - github.com/BenjaminAbt - Sustainable Code