Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Potential upgrade problem with XMLHttpRequest

$
0
0

My problem isn’t real yet but I’m taking a look at future upgrading routes. In one app XMLHttpRequest is used to call a web API service. Nothing funny about that. I have benched passing parameters as well as using FormData but my problem is specific to passing objects. 

With the new approach API uses the format:

[HttpPost]

public IActionResult Post([FromBody]MyDataEntity myDataEntity)

{ …..

[HttpPut("{id}")]

public IActionResult Put(int id, [FromBody]MyDataEntity myDataEntity)

{…..

Using XMLHttpRequest to post an object works as expected and binds data as expected:

var dataItem = { Key: 1, Name: "Item1", IsComplete: false };

var dataToSend = JSON.stringify(dataItem)

var xhr = new XMLHttpRequest();

xhr.open('POST', '/api/ValueUsingObject/', true);

xhr.responseType = 'text';

xhr.setRequestHeader('Content-type', 'application/json;');

xhr.onreadystatechange = function () {

if (xhr.readyState == 4)

{

if (xhr.status == 204 || xhr.status == 200)//Success

{

 //Do whatever

}

}};

xhr.send(dataToSend);

Now the question: How would one handle the PUT? If I execute xhr.open('PUT', '/api/ValueUsingObject/1', true) the API function executes, id has a value but the object data does not bind. Obviously if I add the id to the dataItem the signature will not match and if I don’t specify the id the call will just return 404. Is there a way to handle this or should I just remove the id from the Put function and integrate it into the entity and then add it as a key value pair to my xhr data as I use to do with the old API?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>