简体   繁体   English

文件/图像上传后 ASP.NET 3.0 mvc 应用程序崩溃

[英]ASP.NET 3.0 mvc app crash after file/image upload

I am using ASP.Net Core 3.0 and I want to create a new product with images but my app crashes after i choose the image from the file upload and push the 'create' button.我正在使用 ASP.Net Core 3.0,我想创建一个带有图像的新产品,但是在我从文件上传中选择图像并按下“创建”按钮后,我的应用程序崩溃了。 I tried to debug on my controller but the app crashes before it reaches the controller.我试图在我的控制器上调试,但应用程序在它到达控制器之前崩溃了。 Everything else is working on create action.其他一切都在创建操作上。 When I comment out the file input, everything else works fine.当我注释掉文件输入时,其他一切正常。 I just want the image to be posted with the rest of my ProductModelVM so I can handle then in my controller.我只想将图像与我的 ProductModelVM 的其余部分一起发布,以便我可以在我的控制器中处理。

Here is my ProductPostVM model:这是我的 ProductPostVM 模型:

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace WebshopAppMVC.Models
{
    public class ProductPostVM
    {
        //[JsonPropertyName("id")]
        //public int Id { get; set; }
        [Required]
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("description")]
        public string Description { get; set; }
        [Required]
        [JsonPropertyName("price")]
        public double Price { get; set; }
        [Required]
        [JsonPropertyName("manufacturerId")]
        // A product has one manufacturer
        public int ManufacturerId { get; set; }
        [Required]
        [JsonPropertyName("categories")]
        // products can have many Categories
        public ICollection<int> Categories { get; set; }
        [JsonPropertyName("images")]
        // one product can have many images
        public IEnumerable<IFormFile> Images { get; set; }
    }
}

Here is my Create.cshtml:这是我的 Create.cshtml:

@model WebshopAppMVC.Models.ProductPostVM
@using System.Text.Json;
@using WebshopAppMVC.Models;
@using Microsoft.AspNetCore.Http;

@{
    ViewData["Title"] = "Create";
    List<ManufacturerVM> manufacturers = JsonSerializer.Deserialize<List<ManufacturerVM>>(@Context.Session.GetString("manufacturers"));
    SelectList manufacturersData = new SelectList(manufacturers, "Id", "Name");
    List<CategoryVM> categories = JsonSerializer.Deserialize<List<CategoryVM>>(@Context.Session.GetString("categories"));
}

<h1>Create</h1>

<h4>ProductPostVM</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @*<div class="form-group">
        <label asp-for="Id" class="control-label"></label>
        <input asp-for="Id" class="form-control" />
        <span asp-validation-for="Id" class="text-danger"></span>*@
            @*</div>*@
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ManufacturerId" class="control-label"></label>
                <select asp-for="ManufacturerId" class="form-control" asp-items=@manufacturersData>
                    <option value="">Please select</option>
                </select>
                <span asp-validation-for="ManufacturerId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Categories" class="control-label"></label>
                <div class="col-md-offset-2 col-md-10">
                    <table>
                        <tr>
                            @{
                                int cnt = 0;

                                foreach (var category in categories)
                                {
                                    if (cnt++ % 3 == 0)
                                    {
                                    @:</tr><tr>
                                    }
                                    @:<td>
                                        <input type="checkbox"
                                               name="Categories"
                                               value="@category.Id"
                                               @(Html.Raw(category.Assigned ? "checked=\"checked\"" : "")) />
                                        @category.Name
                                    @:</td>
                                }
                            @:</tr>
                            }
                        </table>
                    </div>
                </div>
            <div class="form-group">
                <dl>
                    <dt>
                        <label asp-for="Images"></label>
                    </dt>
                    <dd>
                        <input asp-for="Images" type="file" multiple>
                    </dd>
                </dl>
            </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>

    <div>
        <a asp-action="Index">Back to List</a>
    </div>

and this is the code in my controller for the create action:这是我的控制器中用于创建操作的代码:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(ProductPostVM productPost)
        {
            if (ModelState.IsValid)
            {
                //foreach (string file in Request.)
                //{
                //    var postedFile = Request.Files[file];
                //    postedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(postedFile.FileName));
                //}
                var client = _httpClientFactory.CreateClient();

                var productContent = new StringContent(JsonSerializer.Serialize(productPost), Encoding.UTF8, "application/json");

                HttpResponseMessage httpResponseMessage = await client.PostAsync(new Uri("https://localhost:44352/api/products"), productContent).ConfigureAwait(false);

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    return RedirectToAction(nameof(Index));
                }
            }

            return View(productPost);
        }

Here is a picture of how my view looks:这是我的视图外观的图片:

创建.cshtml

This behavior in specific has been attributed to a browser problem and not Visual Studio in general.这种行为具体归因于浏览器问题,而不是一般的Visual Studio As per this article and this article , this behavior was generally observed when using browsers like Brave in this case and Yandex .根据这篇文章和这篇文章,在这种情况下使用BraveYandex等浏览器时,通常会观察到这种行为。 Sometimes even Chrome shows this behavior but it is not consistent (at least that is what I have observed).有时甚至Chrome也会显示这种行为,但它并不一致(至少这是我观察到的)。

A possible solution would be changing your browser type to use ideal browsers like Chrome, Firefox or Edge.一个可能的解决方案是更改您的浏览器类型以使用理想的浏览器,如 Chrome、Firefox 或 Edge。

Your <form> tag is using the wrong method attribute.您的<form>标签使用了错误的方法属性。 method="get" is the default value . method="get"默认值

Try尝试

<form asp-action="Create" enctype="multipart/form-data" method="post">

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM