Sunday, 15 June 2014

c# - Web API 2 returning text/plain responses -



c# - Web API 2 returning text/plain responses -

really struggling hope people here can help with. i'm writing restful api in web api 2. whenever send request service, response consistently beingness sent content-type of text/plain. no good, response needs content-type of application/json. i've tried few suggestions found google don't think i'm understanding whole picture.

is there special need in order have web service respond application/json content? note want work globally across whole app, i'm not after way modify given response , set content type - want default behaviour whole web service: if request contains accept header application/json want web service homecoming content-type instead of text/plain.

edit clarify:

my response contains object called "responsedata" should serialized json , included in body. i'm putting response this:

httpresponsemessage response = request.createresponse(httpstatuscode.ok, responsedata); homecoming response;

responsedata poco. get's correctly serialized json , returned in response - missing part content-type incorrectly set "text/plain". manually alter on every single response compose, i'm wanting configure on global level.

ok, assuming responsedata string, content-type header text/plain when create httpresponsemessage. doesn't matter contents of string are, since no effort made determine this.

the solution create appropriate content object message, initialized media type you're returning:

httpresponsemessage response = new httpresponsemessage() { content = new stringcontent( responsedata, encoding.utf8, "application/json" ) };

there other methods amount returning particular object type , letting api libraries serialize json or xml required. prefer allow framework work me possible, how you'd accomplish string you've created yourself.

for strict json-only result, remove xml formatter webapi configuration , homecoming poco.

in app_start\webapiconfig.cs, add together next webapiconfig.register method:

config.formatters.remove(config.formatters.xmlformatter);

and api:

public class myobject { public bool result; public string reason; } public class testcontroller : apicontroller { public myobject getdata() { myobject result = new myobject { result = "true", reason = "testing poco return" }; homecoming result; } }

i ran , requested /api/test chrome, doesn't mention application/json in accept header. here response headers until hits content-type:

http/1.1 200 ok cache-control: no-cache pragma: no-cache content-type: application/json; charset=utf-8

and body:

{"result":true,"reason":"testing poco return"}

since disabled xml defaulted json.

c# asp.net-mvc json asp.net-web-api2

No comments:

Post a Comment