So habe ich eine Verwaltungsanwendung, wo ein Benutzer ein Produkt der Datenbank über die API hinzufügen kann. Die Funktionen in der API funktionieren gut, weil ich dies mit Postboten getestet habe. Allerdings werde ich es wahrscheinlich falsch auf die Web-API hochladen, und ich weiß nicht warum.C# bekomme 500 Fehler vom Server beim Hochladen von Multipartform mit Bild zu API
Die Web-API ist eine ASP.NET CORE-Web-API. Ans meine Verwaltung ist eine Windows Forms-Anwendung, ja ich weiß, es ist nicht die beste Wahl. Aber irgendwie ist hier, wie ich versuche, das Formular auf den Web-API von der Anwendung zu laden:
Die Upload-Aktion der Form:
private void buttonToevoegen_Click(object sender, EventArgs e)
{
if (textArtikelNaam.Text == "")
{
MessageBox.Show("Artikelnaam is leeg, voeg text toe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (textArtikelOmschrijving.Text == "")
{
MessageBox.Show("Artikel omschrijving is leeg, voeg text toe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (textArtikelPrijs.Text == "")
{
MessageBox.Show("Artikel prijs, voeg text toe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (comboBoxType.Text == "")
{
MessageBox.Show("Selecteer type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (buttonSelecteerAfbeelding.Text == "")//werkt nog niet
{
MessageBox.Show("Selecteer afbeelding", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
ToevoegProduct product = new ToevoegProduct();
product.ProductNaam = textArtikelNaam.Text;
product.ProductPrijs = Convert.ToInt32(textArtikelPrijs.Text);
product.ProductBeschrijving = textArtikelOmschrijving.Text;
product.ProductType = comboBoxType.Text;
product.ProductAfbeelding = imageArtikel.Image;
product.ProductWinkel = 1;
product.ProductDirectLeverbaar = false; //niet nodig.
product.ProductKorting = 0;
product.ProductVoorraad = 1;
API.postProductMulti("products", product, "toevoegen");
MessageBox.Show("Product is correct toegevoegd!", "Gelukt!", MessageBoxButtons.OK, MessageBoxIcon.Information);
ProductenOverzicht f7 = new ProductenOverzicht();
Hide();
f7.Show();
}
die API-Klasse Funktion:
public static async void postProductMulti(string model, Models.ToevoegProduct product, string optionalRoute = null)
{
HttpClient client = new HttpClient();
MultipartFormDataContent mfdc = new MultipartFormDataContent();
// create the communication to the model from the API.
string apiposturl = apiurl;
apiposturl += model;
if (optionalRoute != null)
apiposturl += ("/" + optionalRoute);
byte[] bytes;
using (var ms = new MemoryStream())
{
product.ProductAfbeelding.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
bytes = ms.ToArray();
}
mfdc.Add(new StringContent(product.ProductNaam), "productNaam");
mfdc.Add(new StringContent(product.ProductPrijs.ToString()), "productPrijs");
mfdc.Add(new StringContent(product.ProductBeschrijving), "productBeschrijving");
mfdc.Add(new StringContent(product.ProductType), "productType");
mfdc.Add(new StringContent(product.ProductKorting.ToString()), "productKorting");
mfdc.Add(new StringContent(product.ProductVoorraad.ToString()), "productVoorraad");
mfdc.Add(new StringContent(product.ProductDirectLeverbaar.ToString()), "productDirectLeverbaar");
mfdc.Add(new ByteArrayContent(bytes, 0, bytes.Length), "productAfbeelding");
HttpResponseMessage response = await client.PostAsync(apiposturl, mfdc);
response.EnsureSuccessStatusCode();
client.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
}
Und dies ist mein ToevoegProduct Modell:
namespace FlowerPower.Models
{
class ToevoegProduct
{
public int Id { get; set; }
public string ProductNaam { get; set; }
public int ProductPrijs { get; set; }
public string ProductBeschrijving { get; set; }
public string ProductType { get; set; }
public int ProductKorting { get; set; }
public int ProductVoorraad { get; set; }
public bool ProductDirectLeverbaar { get; set; }
public Image ProductAfbeelding { get; set; }
public int ProductWinkel { get; set; }
}
}
Und meine das ist, was meine API w tun Henne diese Aktion angefordert:
Die Add Aktion im Produkt Controller:
[HttpPost("toevoegen")]
[EnableCors("AllowAnyOrigin")]
public async Task<IActionResult> PostProduct([FromForm] AddedProduct product)
{
// Kijk of het huidige model geldig is.
// Zo niet dan wordt een een BadRequest code weergegeven.
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Upload de meegegeven afbeelding naar de website en database.
FileUploader.UploadFile(product.ProductAfbeelding);
// Voeg het product toe aan de database.
_context.Product.Add(ConvertAddedToProduct(product, FileUploader.UploadedUrl)[0]);
await _context.SaveChangesAsync();
// Ga naar GetProduct, dit stuurt het aangemaakte product terug.
return CreatedAtAction("GetProduct", new { id = product.Id }, product);
}
Und das ist das addedproduct Modell in meinem API.
public class AddedProduct
{
public int Id { get; set; }
public string ProductNaam { get; set; }
public int ProductPrijs { get; set; }
public string ProductBeschrijving { get; set; }
public string ProductType { get; set; }
public int ProductKorting { get; set; }
public int ProductVoorraad { get; set; }
public bool ProductDirectLeverbaar { get; set; }
public IFormFile ProductAfbeelding { get; set; }
public int ProductWinkel { get; set; }
}
Ich möchte auch nicht meine API ändern, weil ich weiß, dass es funktioniert und dass es möglich ist.
Wie gewünscht mein Postbote:
Und das ist die Ausnahme:
System.Net.Http.HttpRequestException aufgetreten HResult = 0x80131500 Message = Antwort-Statuscode nicht Hinweis Erfolg: 500 (Interner Serverfehler). Source = Stacktrace: bei System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() bei FlowerPower.API.d__3.MoveNext() in C: \ Benutzer \ beren \ Source \ Repos \ FlowerPowerAPI \ FlowerPower1 \ API.cs: Zeile 133
Können Sie die Ausnahme und Stack-Trace vom Server veröffentlichen? – john
Mit Blick auf Ihren Code, ich vermute, dass Sie 'FormUrlEncodedContent' benötigen, die alle Ihre Formularwerte enthält, im Gegensatz zu vielen' StringContent' Teilen. Ich könnte sicherer sein, wenn ich die Arbeit des Postboten und die Antwort sehen könnte. – john
Ich habe einen Screenshot von Postboten und die Ausnahme hinzugefügt, die ich –