unable to return json data, WCF Resful Service .NE

2019-05-21 01:53发布

问题:

I recently set up a WCF Resful Service with Entity Framework 4.0 It works with XML perfectly, however when I try to return it in json format I got

HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html
Connection: close
Timestamp: 01:11:06.453

ReadResponse() failed: The server did not return a response for this request.

Any Ideas??

thanks in advance

Edit: The Code is quite normal, actually i tried two way of doing it, but no luck.

Hard code ResponseFormat Way:

[OperationContract]
        [WebInvoke(Method = "GET",
            BodyStyle = WebMessageBodyStyle.Wrapped,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "Deal/{id}")]
        Deals XMLDealDetail(string id);

Dynamically Set ResponseFormat Way:

    [OperationContract]
            [WebInvoke(Method = "GET",
                BodyStyle = WebMessageBodyStyle.Wrapped,
                ResponseFormat = WebMessageFormat.Json,
                UriTemplate = "Deal/{id}/{format}")]
            Deals XMLDealDetail(string id, string format);

    public Deals XMLDealDetail(string id, string format)
            {
                OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;

                if (format.ToLower() == "json")
                {
                    context.Format = WebMessageFormat.Json;
                    context.ContentType = "application/json";
                }
                else
                {
                    context.Format = WebMessageFormat.Xml;
                }
//Deals is a Entity Class defined in edmx file
                    Deals deal = DealsServices.GetById(id);
                    return deal;

            }

where am i missing??

回答1:

By using Service Trace Viewer, actually there a number of ways of getting the problem. This link helped me. I finally see the problem, however being stacked gain with the problem.

'The type 'xxx.DataEntity.AppView' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.'

I will start a new question for that.



回答2:

I had the same problem when I've not set one of the parameters of an object. For example I have a class:

public class Obj {
   int param1 { get; set; }
   int param2 { get; set; }
};

And if param1 or param2 was null or minValue (for DateTime), so I got the problem. When I set all parameters then the problem disappear.