C#开发WebService(XML和JSON),发布在IIS7(一)

开发Android应用,需要服务器,很多人采用Java发布XML或JSON,本人对Java了解不多,所以采用.net开发WebService发布XML或者JSON

Android所需要的XML或者JSON文档,可以采用简单的页面返回,也可以采用wcf编写,一下将两种方式都描述出来,主要目的是记录和自己总结。观点不正确请大家不要拍砖。呵呵

第一种:通过页面返回JSON文档。

1、建立一个ASP.NET项目,然后获取数据库中的某个表的信息,转换成List,然后通过C#提供的类,转换成JSON

数据库中的表结构以及数据如下图

建立ASP.NET应用程序,然后建立一个Model类,结构图如下图

web.config文件的内容

 

<?xml version="1.0"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>  
  <appSettings>
    <add key="dbcon" value="data source=.;integrated security=sspi;initial catalog=DB_Student"/>    
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

 

 

Model项目中BookInfo文件中的代码如下

 

namespace Model
{
    public class BookInfo
    {
        string bookID;

        public string BookID
        {
            get { return bookID; }
            set { bookID = value; }
        }
        string bookName;

        public string BookName
        {
            get { return bookName; }
            set { bookName = value; }
        }
        string author;

        public string Author
        {
            get { return author; }
            set { author = value; }
        }
        string publish;

        public string Publish
        {
            get { return publish; }
            set { publish = value; }
        }
        decimal price;

        public decimal Price
        {
            get { return price; }
            set { price = value; }
        }
        int state;

        public int State
        {
            get { return state; }
            set { state = value; }
        }
    }
}

DB项目中DBHelper文件的代码如下

 

 

namespace DB
{
    public class DBHelper
    {
        public SqlConnection GetCon()
        {
            string strcon =ConfigurationSettings.AppSettings["dbcon"].ToString();
            SqlConnection cn = new SqlConnection(strcon);
            return cn;
        }

        public DataTable GetDataTable(string strSQL)
        {
            SqlConnection cn = this.GetCon();
            SqlDataAdapter da = new SqlDataAdapter(strSQL,cn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }
        public DataTable GetDataTable(SqlCommand  cmd)
        {
            SqlConnection cn = this.GetCon();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }
    }
}

BLL项目中BookInfo的代码如下

 

 

namespace BLL
{
    public class BookInfo
    {
        public DataTable GetBooks()
        {
            DB.DBHelper dbhelper=new DB.DBHelper();            
            string strSQL = "select * from BookInfo";
            DataTable dt = dbhelper.GetDataTable(strSQL);
            return dt;
        }
        public List<Model.BookInfo> GetBookList()
        {
            List<Model.BookInfo> bookList = new List<Model.BookInfo>();
            DataTable dt = this.GetBooks();
            foreach (DataRow dr in dt.Rows)
            {
                Model.BookInfo info = new Model.BookInfo();
                info.BookID = dr["BookID"].ToString();
                info.BookName=dr["BookName"].ToString();
                info.Author = dr["Author"].ToString();
                info.Publish = dr["Publish"].ToString();
                try
                {
                    info.Price = decimal.Parse(dr["Price"].ToString());
                }
                catch
                {
                    info.Price = 0;
                }
                try
                {
                    info.State = int.Parse(dr["State"].ToString());
                }
                catch
                {
                    info.State =1;
                }
                bookList.Add(info);                
            }
            return bookList;
        }
    }
}


Web项目中的Default.aspx文件的代码如下:

 

 

protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                List<Model.BookInfo> list = new BLL.BookInfo().GetBookList();
               string strJson= ListToJson(list);
               Response.Write(strJson);
            }
        }

        private string  ListToJson(List<Model.BookInfo> list)
        {
            try
            {
                DataContractJsonSerializer json = new DataContractJsonSerializer(list.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    json.WriteObject(ms, list);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return "";
            }
        }

在Web项目中需要添加引用:System.Runtime.Serialization,才能够使用DataContractJsonSerializer类,最后返回的结果为:

 

 

2、发布到IIS服务器上

首先将IIS7配置好,然后再IIS7上建立一个网站,并设置好虚拟目录,如图

然后再VS2010中配置发布

访问的效果如图

那是因为.NET 框架的版本号未2.0,需要改成4.0

访问后效果

再次修改IIS的配置,在应用程序池中,选择MyWeb的高级设置,设置标示为LocalSystem即可

然后再次访问,就能访问到正确结果了。

posted @ 2014-11-29 17:05  chenlinyunyi  阅读(1036)  评论(0编辑  收藏  举报