简体   繁体   English

返回JSON而不是XML Web服务

[英]Return JSON instead of XML web service

I'm wanting my web service to return JSON not XML, currently it's returning JSON wrapped in XML. 我想让我的Web服务返回JSON而不是XML,目前它正在返回以XML包装的JSON。 View the source of my URL http://soulappvm.cloudapp.net/SAService/Service.svc/userlist produces the following... 查看我的URL的源http://soulappvm.cloudapp.net/SAService/Service.svc/userlist会生成以下内容...

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"Name":"Daniel1user","Password":"40d5e24c5c906103a980ec7c69c100c5","Address":"123 st"},{"Name":"Daniel2user","Password":"90a1587cbe37d4a2a128ce758f338587","Address":"1234 st"},{"Name":"Daniel3user","Password":"f97c27c65d3af0d18657cbae16f9d57e","Address":"ccc"},{"Name":"user1user","Password":"def907bec025cd03bf738c3612bd7926","Address":"ds"},{"Name":"user2user","Password":"0fa04e1c4a5720195b106df9e746a72b","Address":"ff"}]</string>

Is there simple way to get it to just return JSON? 有简单的方法让它只返回JSON吗? I have tried ResponseFormat = WebMessageFormat.Json but that did not work. 我试过ResponseFormat = WebMessageFormat.Json但是没有用。

IService 服务

namespace SoulInfoService
{

    [ServiceContract(SessionMode = SessionMode.Allowed, Namespace = "http://mmmkay95989.wix.com/bb2soulinfo")]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate = "id")]
        //[AspNetCacheProfile("CacheFor1200Seconds")]
        string ServiceID();

        [OperationContract]
        [WebGet(UriTemplate = "version")]
        //[AspNetCacheProfile("CacheFor1200Seconds")]
        string Version();

        [OperationContract]
        [WebGet(UriTemplate = "userlist", ResponseFormat = WebMessageFormat.Json)]
        [AspNetCacheProfile("CacheFor1200Seconds")]
        string UserList();

        [OperationContract]
        [WebGet(UriTemplate = "usersearch?term={term}")]
        User[] UserSearch(string term);

        [OperationContract]
        [WebGet(UriTemplate = "soulimg?id={id}")]
        Stream SoulImage(string id);

        [OperationContract]
        [WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
        void GetOptions();

    } // interface
}

Service 服务

namespace SoulInfoService
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        public Service()
        {
            serviceID = Guid.NewGuid();
        } // Service

        public string ServiceID()
        {
            string rval = "";
            rval = serviceID.ToString();
            return rval;
        } // ServiceID

        public string Version()
        {
            return "1.0.0";
        } // Version

        public void GetOptions()
        {
        } // GetOptions




        public string UserList()
        {
            User[] rval = null;
            using (var sqlCommand = new SQLiteCommand("SELECT * FROM Users"))
            {
                rval = GetUsers(sqlCommand);
            }


            return JsonConvert.SerializeObject(rval);
            //return rval;
        } // UserList

        public User[] UserSearch(string term)
        {
            User[] rval = null;
#if SANITY_CHECK
         term = Sanitize(term);
#endif
            string sqlString = String.Format("SELECT * FROM Users WHERE username LIKE '%{0}%'", term);
            using (var sqlCommand = new SQLiteCommand(sqlString))
            {
                rval = GetUsers(sqlCommand);
            }
            for (int i = 0; i < rval.Length; i++)
            {
                System.Diagnostics.Debug.WriteLine("value: " + rval[i].Name);
            }

            return rval;
        } // UserSearch

        public Stream SoulImage(string id)
        {
            string categoryFolder = "/Souls/";
            return GetImage(id, categoryFolder);
        } //SoulImage

        private Stream GetImage(string id, string categoryFolder)
        {
            string mimeType = "image/jpeg";
            string fileExtension = "jpg";
            ConfigReader config = new ConfigReader();
            string dataRoot = config.GetString(CONFIG_DATA_ROOT, @"C:/");
            string img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
            MemoryStream ms = null;
            if (!File.Exists(img))
            {
                mimeType = "image/gif";
                fileExtension = "gif";
                img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
                if (!File.Exists(img))
                {
                    mimeType = "image/png";
                    fileExtension = "png";
                    img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
                    if (!File.Exists(img))
                    {
                        img = dataRoot + "/Images/Default.png";
                    }
                }
            }
            ms = new MemoryStream(File.ReadAllBytes(img));
            WebOperationContext.Current.OutgoingResponse.ContentType = mimeType;
            return ms;
        } // GetImage



        private User[] GetUsers(SQLiteCommand command)
        {
            var list = new List<User>();
            try
            {
                using (SQLiteConnection dbConnection = OpenDBConnection())
                {
                    command.Connection = dbConnection;
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var b = new User()
                            {
                                //Id = reader["TextId"].ToString(),
                                Name = reader["Username"].ToString(),
                                Password = reader["Password"].ToString(),
                                Address = reader["Address"].ToString(),
                            };
                            list.Add(b);
                        }
                        reader.Close();
                    }
                    dbConnection.Close();
                }
            }
            catch (Exception ex)
            {
                string tmp = ex.Message;
            }
            return list.ToArray();
        } // GetUsers

        private static string Sanitize(string term)
        {
            Regex rgx = new Regex(@"[^\p{L}\p{N} ]+"); // \p{L} matches Unicode letters while \p{N} matches Unicode digits
            term = rgx.Replace(term, ""); // Strip anything that isn't a letter or digit
            return term;
        } // Sanitize

        private SQLiteConnection OpenDBConnection()
        {
            ConfigReader config = new ConfigReader();
            string dataRoot = config.GetString(CONFIG_DATA_ROOT, @"C:/");
            string dataDb = dataRoot + "/" + config.GetString(CONFIG_DATABASE, @"");
            //string dataDb = dataRoot + "/" + databaseID;
            string connectionString = String.Format("Data Source={0};Version=3;", dataDb);
            SQLiteConnection dbConnection = new SQLiteConnection(connectionString);
            dbConnection.Open();
            return dbConnection;


        } // OpenDBConnection

        /// <summary>
        /// Adds access control headers to service methods. One will need to add this when using
        /// the Development Server which does not use system.webServer section of the Web.config 
        /// file and thus add the custom headers in there.
        /// </summary>
        private void AddAccessControlHeaders()
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Authorization, Content-Type");
        } // AddAccessControlHeaders

        private readonly string CONFIG_DATA_ROOT = "DataRoot";
        private readonly string CONFIG_DATABASE = "Database";
        private readonly string CONFIG_REALM = "Realm";
        private readonly Guid serviceID;
    } // class

}

Web.config Web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="DataRoot" value="C:/Users/delm959/Documents/Database"/>
    <add key="Database" value="TestDatabase.db"/>
    <add key="Realm" value="Boutique Cassee"/>
  </appSettings>

  <!--
    For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.5" />
      </system.Web>
  -->
  <system.web>
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.5"/>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor1200Seconds" duration="1200" varyByParam="none" varyByHeader="Accept"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    <pages controlRenderingCompatibilityVersion="4.0"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="DefaultEndPointBehavior">
          <dataContractSerializer maxItemsInObjectGraph="10000"/>
        </behavior>
        <behavior name="RESTEndPointBehavior">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="WebHttpBindingConfig">
          <!-- Comment out the security for HTTP; uncomment the security for HTTPS -->
          <!--<security mode="Transport">
                  <transport clientCredentialType="None" />
               </security>-->
        </binding>
      </webHttpBinding>
      <basicHttpBinding>
        <binding name="BasicHttpBindingConfig">
          <readerQuotas/>
          <!--
               <security mode="None"/>
               -->
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="SoulInfoService.Service">
        <endpoint address="" behaviorConfiguration="RESTEndPointBehavior"
          binding="webHttpBinding" bindingConfiguration="WebHttpBindingConfig"
          bindingNamespace="http://www.example.org/Samples" contract="SoulInfoService.IService" />
        <endpoint address="soap" behaviorConfiguration="DefaultEndPointBehavior"
          binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig"
          bindingNamespace="http://www.example.org/Samples" contract="SoulInfoService.IService" />
        <endpoint address="mex" binding="mexHttpBinding" bindingNamespace="http://www.example.org/Samples"
          contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Request-Method" value="OPTIONS, GET, POST"/>
        <add name="Access-Control-Allow-Credentials" value="true"/>
        <add name="Access-Control-Allow-Headers" value="Authorization, Content-Type"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

This is a quite good tutorial how to create RESTful service with WCF which uses JSON formatter. 这是一个很好的教程,说明如何使用使用JSON格式程序的WCF创建RESTful服务。

http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM