首页 > 解决方案 > 远程验证因 IFormFile 属性而失败

问题描述

我注意到 ASP.NET 核心中的远程验证总是失败,因为服务器总是在控制器方法中收到一个空 IFormFile。有没有办法让它工作?一些重现问题的代码:

模型类(“未映射”已包含在内,因此实体框架不会干扰,但它在没有实体框架的另一个项目中也不起作用。

public class Movie
{
    public int ID { get; set; }
    [Sacred(sacredWord: "sonda")]
    public string Title { get; set; }

    [Display(Name = "Release Date")]
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }

    [Column(TypeName = "decimal(18, 2)")]
    public decimal Price { get; set; }

    [Remote(action: "VerifyRating", controller: "Movies")]
    public string Rating { get; set; }

    [NotMapped]
    [Remote(action: "VerifyFile", controller: "Movies"),Required]
    public IFormFile File { get; set; }
}

控制器

public class MoviesController : Controller
{
    private readonly WebAppMVCContext _context;

    public MoviesController(WebAppMVCContext context)
    {
        _context = context;
    }



    // GET: Movies/Create
    public IActionResult Create()
    {
        return View();
    }

    [AcceptVerbs("Get", "Post")]
    public IActionResult VerifyFile(IFormFile File)
    {
        if(File == null)
        {
            return Json("The file is null");

        }
        else
        {
            return Json("The file is not null");
        }
    }


    // POST: Movies/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            _context.Add(movie);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }       

    [AcceptVerbs("Get", "Post")]
    public IActionResult VerifyRating( int rating)
    {
        if(rating>0 && rating < 10)
        {
            return Json(true);
        }
        else
        {
            return Json($"The rating is invalid");
        }
    }

和视图

@model WebAppMVC.Models.Movie

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" 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="Rating" class="control-label"></label>
                <input asp-for="Rating" class="form-control" />
                <span asp-validation-for="Rating" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="File" class="control-label"></label>
                <input asp-for="File" />
                <span asp-validation-for="File" class="text-danger"></span> 
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

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

@section Scripts{
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}


    <script type="text/javascript">
        $.validator.addMethod('sacred',
            function (value, element, params) {
                var title = $(params[0]).val(),
                    sacredword = params[1];
                if (title!=null && title == sacredword) {
                    return true;
                }
                else {
                    return false;
                }
            }
        );
        $.validator.unobtrusive.adapters.add('sacred',
            ['sacredword'],
            function (options) {
                var element = $(options.form).find('input#Title')[0];
                options.rules['sacred'] = [element, options.params['sacredword']];
                options.messages['sacred'] = options.message;
            }
        );
    </script>
}

请注意,所有其他验证都有效(包括远程验证“VerifyRating”)。

标签: asp.net-core-mvcasp.net-core-2.1

解决方案


推荐阅读