简体   繁体   English

将带有图像的多部分表单上传到 API 时,C# 从服务器获取 500 错误

[英]C# getting 500 error from server when uploading multipartform with image to API

So I have a management application where a user can add a product to the database through the API.所以我有一个管理应用程序,用户可以通过 API 将产品添加到数据库中。 The functions in the API work fine because I have tested this with postman. API 中的函数工作正常,因为我已经用邮递员测试过了。 However, I am probably uploading it incorrectly to the Web API, and I don't know why.但是,我可能错误地将其上传到 Web API,我不知道为什么。

The Web API is an ASP.NET CORE Web API. Web API 是一个 ASP.NET CORE Web API。 Ans my management is a Windows Forms application, yes I know it's not the best choice. Ans 我的管理是 Windows 窗体应用程序,是的,我知道这不是最佳选择。 But anyways here is how I try to upload the form to the Web API from the application:但无论如何,这是我尝试将表单从应用程序上传到 Web API 的方法:

The upload action of the 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();
        }

the API class function: 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;
    }

And this is my ToevoegProduct model:这是我的 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; }
    }
}

And my this is what my API will be doing when this action is requested:这就是我的 API 在请求此操作时将执行的操作:

The add action in the product 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);
    }

And this is the addedproduct model in my API.这是我的 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; }
}

I also don't want to change up my API because I know that it works and that it's possible.我也不想更改我的 API,因为我知道它可以工作并且是可能的。

As requested my postman:按照我的邮递员的要求:

在此处输入图片说明

And this is the exception:这是例外:

System.Net.Http.HttpRequestException occurred HResult=0x80131500 Message=Response status code does not indicate success: 500 (Internal Server Error). System.Net.Http.HttpRequestException 发生 HResult=0x80131500 Message=响应状态代码未指示成功:500(内部服务器错误)。 Source= StackTrace: at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() at FlowerPower.API.d__3.MoveNext() in C:\\Users\\beren\\Source\\Repos\\FlowerPowerAPI\\FlowerPower1\\API.cs:line 133 Source= StackTrace:在 System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() 在 FlowerPower.API.d__3.MoveNext() 在 C:\\Users\\beren\\Source\\Repos\\FlowerPowerAPI\\FlowerPower1\\API.cs:line 133

I fixed this issue with another solution.我用另一个解决方案解决了这个问题。 I used RestSharper, because that is what postman uses for C#.我使用了 RestSharper,因为这是 postman 用于 C# 的。 With the use of RestSharper came a couple of changes.随着 RestSharper 的使用,带来了一些变化。 I had to change the post function in my API class and the way how I was filling my model.我不得不更改 API 类中的 post 函数以及填充模型的方式。

This is how I'm filling my model now:这就是我现在填充模型的方式:

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

and this is the post method in the API class of the client:这是客户端 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);
    }

This solved my problem.这解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 500 px API与C#引发500内部服务器错误 - 500 px api with C# throwing 500 Internal Server Error 更新一个问题以使用Rest API C#替换服务器并获得500 Internal Server Error - Update an issue to redmine server using Rest API C# and getting 500 Internal Server Error 出现错误:使用 AJAX POST 到 C# Webmethod 时出现 500 内部服务器错误 - Getting Error: 500 Internal server error when using AJAX POST to C# Webmethod C# Web API - 内部服务器错误 500 - C# Web API - Internal Server Error 500 Azure - C# - 使用 Rest 上传图像时出错 API - Azure - C# - Error while uploading image using Rest API 500:尝试从C#控制台调用REST API时发生内部服务器错误 - 500: internal server error while trying to call a REST api from C# console 将图像从Android上传到C#会导致错误和图像格式错误 - Uploading image from Android to C# causes error and malformed image C# Web Api; 尝试 POST 时大摇大摆错误 500 - C# Web Api ; Swaggers error 500 when trying to POST 从 C# 访问 Web 服务时出现 500 内部服务器错误 - 500 Internal Server Error when accessing web service from c# 当我尝试从.net(C#)中的`ektron`获取所有`groupid`时出现内部服务器错误500 - Internal server error 500 when I am trying to get all `groupid` from `ektron` in .net (c#)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM