【发布时间】:2019-01-08 15:31:46
【问题描述】:
我正在将我的 MVC .NET Framework 4.7.2 应用程序迁移到 .NET Core 2.1 应用程序。
我的 ViewModel 如下:
public class MyViewModel, IValidatableObject
{
[Required(ErrorMessage = "Please enter a name")]
public string Name { get; set; }
//Other props removed for brevity
}
我有一个 ajax 调用来保存屏幕上的数据,该调用使用如下的 JsonValidationFilter 属性访问 API:
[HttpPost]
[JsonValidationFilter]
[Route("api/MyController/Id}/Save")]
public async Task<IActionResult> SaveAsync(int Id, MyViewModel model)
{
//code removed for brevity
_myService.Save();
return Ok();
}
因此,我的 .NET Framework 版本应用程序的 ValidationFilter 中的代码如下:
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));
}
}
如果我尝试使用名称保存屏幕,我会进入我的 Ajax 调用的错误函数并出现验证警报,并且验证错误包含在 xhr.responseText 中,因此它会显示正如预期的那样。
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);
}
}
我试图在 .NET Core 中重写验证过滤器,如下所示 - 我确实通过 400 请求进入了 Ajax 调用的错误部分,因此显示了验证警报,但它从未完全构建消息,因为 xhr.responseText 总是空白 - 我错过了一些设置吗?
我的 .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);
}
}
【问题讨论】:
-
你能在浏览器中查看响应是否包含正文吗?
-
@poke - 只是在 Chrome 和网络选项卡上查看开发工具,我确实看到了响应 [“请输入名称”] - 但这并没有在我的 Ajax 调用的错误功能中得到体现
-
很奇怪 - 现在看起来 xhr.responseText 正在获取数据但它没有显示在警报中 - 需要查看 displayErrorMessage 函数
标签: c# jquery ajax asp.net-core