質問

I am using asp.net web api and returning my data like this

return Request.CreateResponse<ResponseResult<ProductSearchDto>>(product.Status.Code, product);

This returned nasty and long looking element nodes when I used fiddler to show me the xml(instead of showing me json).

I now fixed this by adding Data Contracts and Data Members to my ResponseResult class, ProductSearchDto class.

However when I want to see how the json looks, fiddler does not display it anymore and say's it is not valid json anymore.

I am guessing that somehow my datacontracts are messing it up.

役に立ちましたか?

解決

I am guessing that somehow my datacontracts are messing it up.

The response content type has pretty little to do with any DataContracts or whatever. ASP.NET Web API uses a notion called content negotiation. This means that if the client requests JSON and if the server supports JSON he's gonna return JSON. Same For XML and other content types as well. So make sure that the client is setting the Accepts: application/json HTTP request header if you expect JSON from the server.

Here's an example of how a valid request might look like:

GET /api/values/123 HTTP/1.1
Host: example.com
Accept: application/json 
Connection: close

and a sample response from the server:

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 13

{"foo":"bar"}

And here's the sample controller:

public class ValuesController: ApiController
{
    public HttpResponseMessage Get(string id)
    {
        return Request.CreateResponse(HttpStatusCode.OK, new { foo = "bar" });
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top