返回JSON而不是XML Web服务

时间:2016-02-18 22:23:07

标签: c# json web-services

我希望我的Web服务返回JSON而不是XML,目前它返回的是包装在XML中的JSON。查看我的网址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>

有没有简单的方法让它只返回JSON?我尝试了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
}

服务

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

<?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>

1 个答案:

答案 0 :(得分:0)

这是一个非常好的教程,如何使用WSON格式化程序创建RESTful服务。

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