Steve
Steve

Reputation: 4463

How to add backslash into json string as my web api request?

I have this Javascript code which get the form data and, convert the data input into object and then stringify it to send a web api request. How to add backslash into json string as my web api request?

Example from

{"application_name":"test1","application_name_Id":"1225848d-5941-4fac-bdff-7799b53d6fd0"} 

to

{\"application_name\":\"test1\",\"application_name_Id\":\"1225848d-5941-4fac-bdff-7799b53d6fd0\"}

function PostForm() {
        const form = document.querySelector('#myForm');
      
        const data = new URLSearchParams(new FormData(form).entries());
        
        const obj = Object.fromEntries(data); 
        
        for (let key in obj) {
            if (!isNaN(obj[key])) {
                obj[key] = Number(obj[key]);
            }
        }

        const stringifyObj = JSON.stringify(obj);
        console.log(stringifyObj)

        $.ajax({
            url: 'https://localhost:7273/WeatherForecast',
            type: 'POST',
            data: stringifyObj,
            dataType: 'json',
            contentType: "application/json;charset=utf-8",
            success: function (response) {
                debugger
                console.log(response);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                debugger
                console.log(XMLHttpRequest.responseText)
            }
        });
    }

In my web api, I am using C#. So this is the code. It works as well. I can see the value in jsonString. But when I change the type from dynamic to string, it doesn't work because the value in jsonString is

"{"application_name":"test1","application_name_Id":"1225848d-5941-4fac-bdff-7799b53d6fd0"}" 

and not

"{\"application_name\":\"test1\",\"application_name_Id\":\"1225848d-5941-4fac-bdff-7799b53d6fd0\"}"

[HttpPost]
public void Post([FromBody] dynamic jsonString)
{
   // code removed as brevity.
}

The code works fine.

If I change to data:obj, I will get this error message

{type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",…}
errors
: 
{$: ["'a' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],…}
status
: 
400
title
: 
"One or more validation errors occurred."
traceId
: 
"00-b01059fa2d870ff1f3e4309f6291cc9e-d02e73b547a874f5-00"
type
: 
"https://tools.ietf.org/html/rfc7231#section-6.5.1"

and this is the payload request.

enter image description here

There is no backslash in jsonstring enter image description here

Unable to deserialize a dynamic type. enter image description here

Upvotes: 1

Views: 857

Answers (1)

shingo
shingo

Reputation: 27011

This is because you tell the server that the data you sent is a json string, the server will then deserialize the string to an object and pass it to the handler.

contentType: "application/json;charset=utf-8",

If you REALLY want to receive a string from the client, change the content type to:

contentType: "text/plain;charset=utf-8",

If you cannot change the content type you can also stringify the string again:

const stringifyObj = JSON.stringify(JSON.stringify(obj));

Upvotes: 2

Related Questions