2017-12-19 2 views
0

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:

enter image description here

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

+0

Können Sie die Ausnahme und Stack-Trace vom Server veröffentlichen? – john

+0

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

+0

Ich habe einen Screenshot von Postboten und die Ausnahme hinzugefügt, die ich –

Antwort

0

Ich habe dieses Problem mit einer anderen Lösung behoben. Ich habe RestSharper verwendet, weil Postman für C# verwendet. Mit der Verwendung von RestSharper kam ein paar Änderungen. Ich musste die Post-Funktion in meiner API-Klasse und die Art und Weise ändern, wie ich mein Modem füllte.

Dies ist, wie ich jetzt mein Modell bin Füllung:

 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.ImageLocation; 
      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(); 
     } 

und dies ist die post-Methode in der API-Klasse des Kunden:

public static 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); 

     var client = new RestClient(apiposturl); 
     var request = new RestRequest(Method.POST); 

     // Zet de headers voor de request. 
     // Dit is bij alles hetzelfde met een multipart/form-data requeset. 
     request.AddHeader("postman-token", "293a9ff3-e250-e688-e20d-5d16ea635597"); 
     request.AddHeader("cache-control", "no-cache"); 
     request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); 
     request.AddHeader("Content-Type", "multipart/form-data"); 

     // Vul de parameters met de waardes van heet model. 
     request.AddParameter("productNaam", product.ProductNaam); 
     request.AddParameter("productBeschrijving", product.ProductBeschrijving); 
     request.AddParameter("productType", product.ProductType); 
     request.AddParameter("productKorting", product.ProductKorting); 
     request.AddParameter("productVoorraad", product.ProductVoorraad); 
     request.AddParameter("productDirectLeverbaar", product.ProductDirectLeverbaar); 
     request.AddFile("productAfbeelding", product.ProductAfbeelding); // Voeg hier het bestandspad in. 
     request.AddParameter("productWinkel", product.ProductWinkel); 

     // Verstuur de request. 
     IRestResponse response = client.Execute(request); 
    } 

Das ist mein Problem gelöst. Danke, dass Sie sich die Zeit genommen haben, meine Frage zu lesen.

Verwandte Themen