jbrabant jbrabant - 1 month ago 14
TypeScript Question

Servicestack request no quotes in json body

Can someone tell me why do I see quotes in my request body in Fiddler and my servicestack request field has none?

POST http://10.255.1.180:8087/testvariables/new/ HTTP/1.1
Host: 10.255.1.180:8087
Connection: keep-alive
Content-Length: 162
Origin: http://10.255.1.180:8087
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
content-type: application/json;charset=UTF-8
Accept: */*
Referer: http://10.255.1.180:8087/certFields
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fr;q=0.6

{"Field":{"Id":67,"Name":"Brightness Reversion","Header":"Brightness Reversion.","Format":"#0.0","Uom":"%","Precision":0,"MapId":8083,"IsMappedToCustomer":false}}


Call from Typescript/Angular2

let body = JSON.stringify(certField);
let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });

let requestoptions: RequestOptions = new RequestOptions({
method: RequestMethod.Post,
url: this._certFieldsUrl + 'new/',
headers: headers,
body: '{"Field":'+body+'}'
})
return this._http.request(new Request(requestoptions))
.toPromise()
.then(function (response) {
return response.json() as CertFieldSaveResponse;
})
.catch(this.handleError);


Request Class

public class CertFieldUpdateRequest : IReturn<TestVariableResponse>
{
public string Field { get; set; }

}


POST Method

public object Post(CertFieldUpdateRequest request)
{
log.Debug(request.Field);
....
}


Inside the service, in the POST method, the value of the request.Field is:

{Id:67,Name:Brightness Reversion,Header:Brightness Reversion.,Format:#0.0,Uom:%,Precision:0,MapId:8083,IsMappedToCustomer:false}

Answer

Its because your body is actually a complete json object and not a string inside a json object. so either:

   let requestoptions: RequestOptions = new RequestOptions({
        method: RequestMethod.Post,
        url: this._certFieldsUrl + 'new/',
        headers: headers,
        body: '{"Field":"'+body+'"}' //See quotes added
        //better: body: {Field : JSON.stringify(body)}
    })

Or make your code class have properties:

   public class CertFieldUpdateRequest : IReturn<TestVariableResponse>
   {
    public Field Field { get; set; }

   }

   public class Field
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Header { get; set; }
        public string Format { get; set; }
        ///etc...
    }
Comments