I need to call a webapi POST method using javascript.
The method accepts a model. I am able to invoke this method correctly from POSTMAN and also see the entries in the database.
// POST api/values
[HttpPost]
public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
{
try
{
Debug.WriteLine("In post method");
var connstr = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
Debug.WriteLine("initializing dbconnection");
var db = new RamDbDataContext(connstr);
Debug.WriteLine("mapping entity");
var inspectionPhoto = new DBLinq.InspectionPhoto
{
InspectionId = iPhoto.InspectionId,
InsertEmployee = iPhoto.Employee,
UpdateEmployee = iPhoto.Employee,
Photo = iPhoto.Data,
InspectionCategoryId = 8,
UpdateDate = DateTime.UtcNow,
InsertDate = DateTime.UtcNow
};
Debug.WriteLine("inserting entity");
db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
db.SubmitChanges();
Debug.WriteLine("done inserting entity");
int id = inspectionPhoto.Id;
return Ok(id);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
return Ok(-1);
}
}
When I try to call this method from javascript, it doesn't reach the endpoint. I have played around with CORS settings but that hasn't helped much.
Here is my javascript code to invoke this method.
<script>
function callwebapi()
{
jsonIn = document.getElementById("mytext").value;
console.log('++As you are+++');
console.log(jsonIn);
console.log('++As you are+++');
const uri = 'https://localhost:44304/api/values';
fetch(uri, {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'PostmanRuntime/7.28.4'
},
body: jsonIn
})
.then(result => console.log(result.status))
.then(response => response.json())
.then(response => console.log('Success: ', response))
.catch(error => console.error('Failure: ', error));
}
</script>
<textarea id="mytext">
{"Id": -1, "InspectionId": 95, "CategoryId": 9, "Employee": "Roger Moore", "Data": null}
</textarea>
<button onclick="callwebapi();">Click this and send your data!</button>
The error I get in the chrome browser console is
TypeError: Failed to fetch at callwebapi (About:89:13) at HTMLButtonElement.onclick (About:110:37)
I created an ASP .NET Web Application and started with web forms project. The client code was created on the About.cshtml page.
I need to eventually merge this code into an existing application. How do I go about fixing this error and making a successful call?
Edit: Postman call request. This is how I am making the call from Postman.