I have a simple viewmodel,
public class AuthenticateViewModel
{
[Required]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
There is a action method with GET and POST
[HttpGet]
[AllowAnonymous]
public IActionResult Authenticate()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Authenticate(AuthenticateViewModel model)
{
if (!ModelState.IsValid)
{
ViewBag.ErrorMessage = "Validation failed";
return View(model);
}
// Do some logic operation
}
I have simple view that displays two text boxes for AuthenticateViewModel and a submit button. The form is posted back to server using Ajax post.
var formData = $("#form-submit").serialize();
$.ajax({
url: targetUrl,
type: "POST",
data: formData,
success: function (response, textStatus, xhr) {
// Do something here
},
error: function (xhr, ajaxOptions, thrownError) {
// Handle error
}
});
So far everything is cool, The form is posting data back to server successfully and my functionality was working perfectly. Later we introduced a middleware, which will read the request payload and logs some information based on the input, which is happening before control reaches to controller action method. You consider it as a RequestMiddleware, sample code given below.
public async Task Invoke(HttpContext httpContext, IRequestLogBuilder requestLogBuilder)
{
var requestPath = httpContext.Request.Path.Value;
var request = httpContext.Request;
if (requestPath != null && ExcludeLogging(requestPath))
{
await _next(httpContext); // Skip logging
return;
}
var originalBodyStream = httpContext.Response.Body;
using (var responseBody = new MemoryStream())
{
try
{
request.EnableRewind();
// use request payload to read some data and log information logic
await _next(httpContext);
// Log some information from response
}
catch (Exception ex)
{
// Handle error scenario
}
}
}
After introducing this middleware on the code, my form started behaving wired. The form works fine for 'x' number of submits and receives response successfully. After that it starts giving me ModelState validation failed messages on the View. The very next form submit is working as expected and it runs successfully. I am unable to identify the root cause about this ModelState validation failure.
After some investigation I found that the model is not populated with the data that was posted by Ajax POST. But I am unable to find out when and where this failure is happening with my form. I have no clue why the default ModelBinding is failed, this behavior is intermittent.
Any help is appreciated.
Thanks.
