System.net.http.mutlipartFormDatacontent -Fehler im Client, der in .NET Framework 4.8 ausgeführt wird, wenn eine VerbindC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 System.net.http.mutlipartFormDatacontent -Fehler im Client, der in .NET Framework 4.8 ausgeführt wird, wenn eine Verbind

Post by Anonymous »

Dies ist mein .NET HTTP-Client-minimal reproduzierbares Beispiel, das eine Verbindung zu einem Server herstellt, der auf einem CNC-Maschinen-Edge-Gerät ausgeführt wird, und eine lokale JSON-Konfigurationsdatei hochgeladen: < /p>

Code: Select all

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace TestClient
{
internal class Program
{
private readonly string _username;
private readonly string _password;
private readonly string _authString;
private readonly HttpClient _client;
public Uri BaseUri { get; }

public Program(string host, int port, string username, string password, bool certify = false)
{
BaseUri = new UriBuilder("https", host, port).Uri;
_username = username;
_password = password;
_authString = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_username}:{_password}"));

var handler = new HttpClientHandler();
if (!certify)
{
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
};
_client = new HttpClient(handler)
{
BaseAddress = BaseUri,
};
}

public async Task SendRequest(HttpMethod method, Uri uri, HttpContent content = null)
{
HttpResponseMessage response;
using (var message = new HttpRequestMessage(method, uri))
{

message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _authString);
message.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
message.Content = content;
await LogRequest(content, message);
response = await _client.SendAsync(message);
}

if (!response.IsSuccessStatusCode)
throw new HttpRequestException(
$"Request failed. Status: {response.StatusCode}.  Reponse:\n{await response.Content.ReadAsStringAsync()}");

return response;
}

private static async Task LogRequest(HttpContent content, HttpRequestMessage message)
{
Console.WriteLine("===HTTP REQUEST===");
Console.WriteLine($"{message.Method} {message.RequestUri} {message.Version}");
foreach (var header in message.Headers)
Console.WriteLine($"{header.Key}: {string.Join(",", header.Value)}");
Console.WriteLine($"");
if (content != null)
{
foreach (var header in content.Headers)
Console.WriteLine($"{header.Key}: {string.Join(",", header.Value)}\n");
Console.WriteLine(await content.ReadAsStringAsync());
}
Console.WriteLine("==================");
}

static async Task Main(string[] args)
{
var host = "123.456.78.901";
var port = 1234;
var username = "User";
var password = "Password";
var filePath = "C:\\Path\\To\\My\\File.json";

try
{
var client = new Program(host, port, username, password);
var endpoint = new UriBuilder(new Uri(client.BaseUri, "amw4analysis/internal/api/job/importjob/"))
{
Query = $"filename={Path.GetFileName(filePath)}"
};
using (var multipartContent = new MultipartFormDataContent())
{
var fileBytes = File.ReadAllBytes(filePath);
var fileName = Path.GetFileName(filePath);
var fileContent = new ByteArrayContent(fileBytes);
multipartContent.Add(fileContent, "file", fileName);

await client.SendRequest(
HttpMethod.Post,
endpoint.Uri,
multipartContent);
}
Console.WriteLine($"Upload of '{filePath}' succeeded");
}
catch (Exception ex)
{
Console.WriteLine($"Upload of '{filePath}' failed\n{ex}");
}
finally
{
Console.WriteLine("Press any key + enter to exit.");
var userinput = Console.ReadLine();
if (userinput != null)
Environment.Exit(0);
}
}
}
}
< /code>
Dies ist das OuPut beim Ausführen der Datei in .net 8.0: < /p>
===HTTP REQUEST===
POST https://123.456.78.901:1234/amw4analysis/internal/api/job/importjob/?filename=File.json 1.1
Authorization: Basic QWRtaW5pc3RyYXRvcjpDQ0FUZWRnZSMy
Accept: */*

Content-Type: multipart/form-data; boundary="e782dc77-b471-4fd5-b982-150db8553fff"

--e782dc77-b471-4fd5-b982-150db8553fff
Content-Disposition: form-data; name=file; filename=File.json; filename*=utf-8''File.json

{
"version": "v1",
"jobConfig": {
"name": "File",
"recordingJobConfiguration": {
"outputStructureType": "SINGLE_FILE",
"outputDataFormat": "JSON",
"autoStop": true
}
}
}
--e782dc77-b471-4fd5-b982-150db8553fff--

==================
Upload of 'C:\Path\To\My\File.json' succeeded
Press any key + enter to exit.
< /code>
Für mein Projekt muss ich den Code in eine ältere Anwendung integrieren, die .NET Framework 4.8 verwendet. Dieser  [b] exakt [/b]  Der gleiche Code schlägt jedoch bei Verwendung von .NET Framework fehl.  Hier ist das aktualisierte Protokoll: < /p>
===HTTP REQUEST===
POST https://123.456.78.901:1234/amw4analysis/internal/api/job/importjob/?filename=File.json 1.1
Authorization: Basic QWRtaW5pc3RyYXRvcjpDQ0FUZWRnZSMy
Accept: */*

Content-Type: multipart/form-data; boundary="b0cb74a9-617d-4d37-9393-e7b95f4dc6e7"

--b0cb74a9-617d-4d37-9393-e7b95f4dc6e7
Content-Disposition: form-data; name=file; filename=File.json; filename*=utf-8''File.json

{
"version": "v1",
"jobConfig": {
"name": "File",
"recordingJobConfiguration": {
"outputStructureType": "SINGLE_FILE",
"outputDataFormat": "JSON",
"autoStop": true
}
}
}
--b0cb74a9-617d-4d37-9393-e7b95f4dc6e7--

==================
Upload of 'C:\Path\To\My\File.json' failed
System.Net.Http.HttpRequestException: Request failed. Status: BadGateway.  Reponse:



502 | Bad Gateway







[img]/Images/MacroSiemens.gif[/img]
502 | Bad Gateway

The application returned an invalid response.





at TestClient.Program.d__8.MoveNext() in C:\Users\CCAT\source\repos\TestClient\TestClient\Program.cs:line 56
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at TestClient.Program.d__10.MoveNext() in C:\Users\CCAT\source\repos\TestClient\TestClient\Program.cs:line 102
Press any key + enter to exit.
< /code>
Hier ist das Protokoll aus dem Server: < /p>
Sep 30 15:19:35 exenia runc[84]: 2025-09-30 15:19:35,106 ERROR --- [http-nio-8090-exec-6] ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request;  nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: java.io.EOFException] with root cause
Sep 30 15:19:35 exenia runc[84]: java.io.EOFException: null
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1303) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1215) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:805) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.coyote.http11.Http11InputBuffer.access$400(Http11InputBuffer.java:42) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.coyote.http11.Http11InputBuffer$SocketInputBuffer.doRead(Http11InputBuffer.java:1185) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:101) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.coyote.http11.Http11InputBuffer.doRead(Http11InputBuffer.java:249) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.coyote.Request.doRead(Request.java:639) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:317) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.InputBuffer.checkByteBufferEof(InputBuffer.java:600) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:340) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at java.io.FilterInputStream.read(FilterInputStream.java:133) ~[?:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:132) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:975) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:879) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at java.io.InputStream.read(InputStream.java:205) ~[?:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:97) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.MultipartStream.readBodyData(MultipartStream.java:572) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.MultipartStream.discardBodyData(MultipartStream.java:596) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.MultipartStream.skipPreamble(MultipartStream.java:614) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.findNextItem(FileItemIteratorImpl.java:228) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.(FileItemIteratorImpl.java:142) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:252) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:276) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.Request.parseParts(Request.java:2932) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.Request.getParts(Request.java:2834) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]:  at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ~[spring-web-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:122) ~[spring-web-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1205) ~[spring-webmvc-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.15.jar!/:5.3.15]
Sep 30 15:19:35 exenia runc[84]: at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar!/:?]
Sep 30 15:19:35 exenia runc[84]: at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.15.jar!/:5.3.15]
Als Referenz hier ist eine funktionierende Curl -Anforderung mit der protokollierten OUPUT:

Code: Select all

 curl 'https://123.456.78.901:1234/amw4analysis/internal/api/job/importjob/?filename=File.json'   \
-H 'Accept: */*'   \
-H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary'   \
-u 'User:Password' \
--data-raw $'------WebKitFormBoundary\r\nContent-Disposition: form-data; name="file"; filename="File.json"\r\nContent-Type: application/json\r\n\r\n{\r\n  "version": "v1",\r\n  "jobConfig": {\r\n    "name": "File",\r\n    "recordingJobConfiguration": {\r\n      "outputStructureType": "SINGLE_FILE",\r\n      "outputDataFormat": "JSON",\r\n      "autoStop": true\r\n    }\r\n  }\r\n}\r\n------WebKitFormBoundary--'\
--insecure \
--verbose
*   Trying 123.456.78.901:1234...
* Connected to 123.456.78.901 (123.456.78.901) port 1234
* ALPN: curl offers h2,http/1.1
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / secp384r1 / RSASSA-PSS
* ALPN: server did not agree on a protocol.  Uses default.
* Server certificate:
*  subject: CN=SIEMENS miniweb; O=Siemens
*  start date: Jun  3 15:27:10 2024 GMT
*  expire date: Jun  5 15:27:10 2027 GMT
*  issuer: CN=SIEMENS miniweb; O=Siemens
*  SSL certificate verify result: self-signed certificate (18), continuing anyway.
*   Certificate level 0: Public key type RSA (2048/112 Bits/secBits), signed using sha512WithRSAEncryption
* using HTTP/1.x
* Server auth using Basic with user 'User'
> POST /amw4analysis/internal/api/job/importjob?filename=File.json HTTP/1.1
> Host: 123.456.78.901:1234
> Authorization: Basic QWRtaW5pc3RyYXRvcjpDQ0FUZWRnZSMy
> User-Agent: curl/8.5.0
> Accept: */*
> Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
> Content-Length: 376
>
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
< HTTP/1.1 200
< Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Tue, 30 Sep 2025 14:05:56 GMT
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< strict-transport-security: max-age=31536000
<
* Connection #0 to host 123.456.78.901 left intact
{"id":"6ed079b9-1980-4a5b-8505-2271ffa1c621","status":"DEACTIVATED","creationTime":null,"lastActivationTime":null,"lastRecordingStartTime":null,"jobStartupFailures":{"lfSignalReadingErrors":[],"hfReadError":false,"lfReadError":false},"configuration":{"id":"faaa7dcb-5560-4833-965b-9554259e9f08","name":"File","description":null,"createTimestamp":null,"modifyTimestamp":null,"metadataLabels":[],"recordingJobConfiguration":{"outputStructureType":"SINGLE_FILE","outputDataFormat":"JSON","autoStop":true},"sinumerikJobConfiguration":{"hfConfiguration":{"groups":[]},"lfConfiguration":{"signals":[]},"sinumerikTriggerConfiguration":{"triggers":[]},"toolingConfiguration":{"coordinateTransformationEnabled":false,"toolParameterRecordingEnabled":false}},"externalSensorJobConfiguration":{"enabled":false,"groups":[]},"dataStreamingJobConfiguration":{"enabled":false,"topicName":null,"fileSize":0},"fanucJobConfiguration":{"signals":[],"fanucTriggerConfiguration":{"triggers":[]}}}}
< /code>
Was fehlt mir? Ich habe versucht, das genaue Curl 
-Anforderungsformat in C# manuell neu zu erstellen, aber das hat den Fehler nicht behoben. Vorschläge werden geschätzt.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post