简体   繁体   中英

Validation Attribute ASP.NET Core

I am migrating my MVC .NET Framework 4.7.2 App to a .NET Core 2.1 App.

My ViewModel is as below:

public class MyViewModel, IValidatableObject
{
    [Required(ErrorMessage = "Please enter a name")]
    public string Name { get; set; }

    //Other props removed for brevity
}

I have an ajax call to save the data on screen which hits an API with a JsonValidationFilter attribute like below:

    [HttpPost]
    [JsonValidationFilter]
    [Route("api/MyController/Id}/Save")]
    public async Task<IActionResult> SaveAsync(int Id, MyViewModel model)
    {
        //code removed for brevity
        _myService.Save();

        return Ok();
    }

So the code in my ValidationFilter for the .NET Framework version of the application is as below:

public class JsonValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid) return;
        var errorMessages = actionContext.ModelState.Values
            .SelectMany(modelState => modelState.Errors.Select(x => x.ErrorMessage));
        actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, Json.Encode(errorMessages));
    }
}

And if I try to save the screen with a name I get into the error function of my Ajax call and the Validation Alert appears and the validation error is contained in the xhr.responseText so it displays as expected.

                error: function (xhr) {

                    $(saveAlertTarget).html('<span class="glyphicon glyphicon-warning-sign"></span>There was a problem with the last save attempt');
                    if (xhr.status == '400') {
                        displayErrorMessage("Please fix validation errors before saving", xhr.responseText);
                    }
                }

I have attempted to rewrite the validation filter in .NET Core as below - and I do get into the error part of my Ajax call with a 400 request so the Validation alert displays but it never builds up the message fully because xhr.responseText is always blank - have I missed something setting this up?

My .NET Core JsonValidationFilter

public class JsonValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        if (actionContext.ModelState.IsValid) return;
        IEnumerable<string> errorMessages = actionContext.ModelState.Values.SelectMany(modelState => modelState.Errors.Select(x => x.ErrorMessage));
        actionContext.Result = new BadRequestObjectResult(errorMessages);
    }
}

这是我的displayErrorMessage Java脚本函数存在的问题-C#.NET Core Json验证筛选器按预期方式工作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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