用Web Service或WCF返回JSON

1. asmx

给类加[System.Web.Script.Services.ScriptService]属性

给方法加[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

web.config,在httpHandler中有两个节点很重要: 
<remove verb="*" path="*.asmx"/> 
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 

注意:HTTP Header的方法 GET, POST, PUT ..., 及Content-Type: application/json; charset=utf-8

2.WCF

SVC文件

[ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ProductService
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "GET", UriTemplate = "/FindByCategoryId?categoryId={categoryId}")]
        public List<Product> FindByCategoryId(int categoryId)
        {
            return ProductHandler.FindByCategoryId(categoryId);
        }      
    }

注意:为Product类加[DataContract]属性,为属性加[DataMember]属性

建议:使用WCF输出的JSON更为完美

posted on 2009-01-15 10:32  yaksea  阅读(2382)  评论(0编辑  收藏  举报