将图像上的多部分上传到API时,C#从服务器获得500错误

问题描述 投票:0回答:1

所以我有一个管理应用程序,用户可以通过API将产品添加到数据库。 API中的函数运行正常,因为我已经使用邮递员对此进行了测试。但是,我可能错误地将它上传到Web API,我不知道为什么。

Web API是ASP.NET CORE Web API。我的管理是一个Windows窗体应用程序,是的,我知道它不是最好的选择。但无论如何,我在这里尝试将表单从应用程序上传到Web API:

表单的上传操作:

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

API类函数:

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

这是我的ToevoegProduct模型:

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

我的这就是我的API在请求此操作时将要执行的操作:

产品控制器中的添加操作:

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

这是我的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; }
}

我也不想改变我的API,因为我知道它有效并且有可能。

根据要求我的邮递员:

enter image description here

这是例外:

发生System.Net.Http.HttpRequestException HResult = 0x80131500消息=响应状态代码未指示成功:500(内部服务器错误)。 Source = StackTrace:位于C:\ Users \ beren \ Source \ Repos \ FlowerPowerAPI \ FlowerPower1 \ API.cs:第133行的FlowerPower.API.d__3.MoveNext()中的System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

c# asp.net api
1个回答
0
投票

我用另一个解决方案解决了这个问题我使用了RestSharper,因为这是邮递员用于C#的东西。随着RestSharper的使用出现了一些变化。我不得不改变我的API类中的post函数以及我填充moedel的方式。

这就是我现在填写模型的方式:

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

这是客户端API类中的post方法:

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

这解决了我的问题。感谢您抽出宝贵时间来查看我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.