Saturday 23 September 2023

"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-c0387627b8818a595c0bc7ab040d6cab-1c6bfb2bcbbca2d3-00","errors":{"data2":["The data2 field is required."],"data3":["The data3 field is required."]}}

Reason for Error: This error occurred when we were posting form data to web API and web API accepting input request parameters as [FromForm] and not all input parameters set as [FromForm].

To regenerate the issue following things need to be done.
1. Create dot net core web API

2. Create an HTML page that posts data to web API

Step 1: Web API -> Input variable name should match with hidden field name.

[HttpPost]

public void Read([FromForm] string data1, string data2, string data3)
{

}

Here, 1st input parameter mark [FromForm] but the other is not set.

Step 2: HTML Form that posts data to web API -> Copy Past HTML in Notepad and Save as dot(.) HTML extension -> Change action with your web API URL

<head>

    <title></title>

</head>

<body onload="this.form1.submit()">

    <form id="form1" method="post" action="https://localhost:7178/api/weatherforecast/read" enctype="multipart/form-data">

       <input type="hidden" name="data1" value="yourdata1">

       <input type="hidden" name="data2" value="yourdata2">

       <input type="hidden" name="data3" value="yourdata3">

    </form>

</body>

</html>

Run the web API application and click to open the saved HTML file. You will receive the error message mentioned above.

Solution to fix this issue.

Way 1 – set [FromForm] attributes to the remaining input parameter.

[HttpPost]

public void Read([FromForm] string data1, [FromForm]  string data2, [FromForm]  string data3)
{

}

 

Way 2 – create a class for the input parameters i.e., the same as the HTML hidden field name.

public class FromFormData
{
    public string data1 { get; set; }
    public string data2 { get; set; }
    public string data3 { get; set; }

}

Change web API input parameter with class FromFormData. Here form1 should match with the HTML form ID name.

[HttpPost]

public void Read([FromForm] FromFormData form1)
{

}

No comments:

Post a Comment