Home > Enterprise >  How to pass additional context along with a Conflict() response
How to pass additional context along with a Conflict() response

Time:07-06

I have a Razor Pages page with some JavaScript sending form data to an API. The API tries to update the database, if there is a concurrency conflict, it returns 409. The JavaScript then checks if the response status is 409 and accordingly alerts the user with a message such as Conflict detected. Q: How do I send back context along with the Response so that the user can see which data has triggered the Conflict?

JavaScript:

var response = await fetch("api/dsr/updateStatus", {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

               if (response.status == 409) {
                    alert("Conflict detected.");
                }

Controller code

IEnumerable<DSR> changedDsrs = // DetectIfConflict();

if (changedDsrs.Any())
{
    return Conflict();
}

I have tried changing the last line to return Conflict(new { statusText = changedDsrs.First().ReleaseId.ToString()}); to no avail. The posted code works fine: if there is indeed a conflict detected than the 409 is returned and the user is alerted - I just want to know how to add context to the alert text to display info from the changedDsrs

CodePudding user response:

Controller:

You can return the following:

if (changedDsrs.Any())
            {
                return Conflict(new { message = $"An existing dsr was found." });
            }

And in JavaScript:

var response = await fetch("api/dsr/updateStatus", {....

response that fetch returned is a JavaScript promise. You can use await on it again to see the properties available.

For example

var text = await response.text();

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

  • Related