目录
(1)创建ASP.NET Web应用程式,如下图:

(2)选择Empty,勾选Web API,点击确定创建,如下图:

(3)创建完成,如下图:

(4)添加文件夹及类,如下图:

说明:BLL(存放数据库相关的类),TestController(接口类),Models(存放Models类),MPage(存放啟動頁面,沒有任何功能)
(1)Web.config配置文件,配置数据库连接及跨域,代码如下:
-
-
-
-
- <add key="DBConnectionString1" value="Data Source=1.3.1.1;Initial Catalog=total;Persist Security Info=True;User ID=SC;Password=SCQSMPTD;MultipleActiveResultSets=true" />
-
- <add key="DBConnectionString2" value="Data Source=1.3.1.3;Initial Catalog=SMT_PCP;Persist Security Info=True;User ID=micro;Password=micro;MultipleActiveResultSets=true" />
-
- <add key="OraConn"
- value="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=1.3.1.22)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PACK)));User Id=e_re;Password=yhong;"/>
-
-
-
-
-
- <add name="Access-Control-Allow-Origin" value="*" />
-
- <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
-
- <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With,token,staffid,timestamp,nonce,signKey,signature" />
-
- <add name="Access-Control-Request-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
-
-
-
-
-
-
(2)在Global.asax文件中添加,下面代码:
- protected void Application_BeginRequest(object sender, EventArgs e)
- {
- var res = HttpContext.Current.Response;
- var req = HttpContext.Current.Request;
-
- //自定义header时进行处理
- if (req.HttpMethod == "OPTIONS")
- {
- res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name,Token,Cookie");
- res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
- res.StatusCode = 200;
- res.End();
- }
- }
(3)啟動頁面:Hello.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Hello.aspx.cs" Inherits="WebAPI.MPage.Hello" %>
-
-
- "http://www.w3.org/1999/xhtml">
- "server">
- "Content-Type" content="text/html; charset=utf-8"/>
-
-
-
- 這個界面只是一個啟動頁面,沒有任何功能
-
-
(4)webapi设置默认返回json格式 ,WebApiConfig文件下Register方法下,添加代码:
- GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
- //默认返回 json
- GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
- new QueryStringMapping("datatype", "json", "application/json"));
-
- // 解决json序列化时的循环引用问题
- config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
(5)BLL文件夹下创建一个SQLHelper类,用于连接数据库,代码:
- using Oracle.ManagedDataAccess.Client;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Text;
- using System.Web;
-
- namespace WebAPI.BLL
- {
- ///
- /// 鏈接類別
- ///
- public enum DBConnList
- {
- DBConnStr1 = 0,
- DBConnStr2 = 1,
- QracleConnS = 2,
- }
- public static class SQLHelper
- {
- //数据库1
- public static string DBConnectionString1 = ConfigurationManager.AppSettings["DBConnectionString1"];
- //数据库2
- public static string DBConnectionString2 = ConfigurationManager.AppSettings["DBConnectionString2"];
- //Qracle数据库操作
- public static string QracleSring = ConfigurationManager.AppSettings["OraConn"];
-
- ///
- /// 獲得數據庫鏈接語句
- ///
- /// 請求數據庫類別
- ///
- public static string GetConnectStr(DBConnList DBConnIndex)
- {
- var connstr = "";
-
- if (DBConnIndex == DBConnList.DBConnStr1)
- {
- connstr = DBConnectionString1;
- }
- else if (DBConnIndex == DBConnList.DBConnStr2)
- {
- connstr = DBConnectionString2;
- }
- else if (DBConnIndex == DBConnList.QracleConnS)
- {
- connstr = QracleSring;
- }
-
- return connstr;
- }
- //SQL 数据库操作
- #region
- ///
- /// 增刪改查,不涉及事物
- ///
- ///
- /// 請求數據庫類別
- ///
- public static int ExecuteSQL(string sql, DBConnList DBConnIndex)
- {
- var connstr = GetConnectStr(DBConnIndex);
-
- SqlConnection conn = new SqlConnection(connstr);
-
- SqlCommand cmd = new SqlCommand(sql, conn);
-
- conn.Open();
-
- int result = cmd.ExecuteNonQuery();
-
- conn.Close();
-
- return result;
- }
-
- ///
- /// 执行带SqlParameter的SQL语句
- ///
- ///
- /// 請求數據庫類別
- /// 參數
- ///
- public static int ExecuteSQLAndSP(string sql, DBConnList DBConnIndex, List
sp ) - {
- var connstr = GetConnectStr(DBConnIndex);
-
- SqlConnection connection = new SqlConnection(connstr);
-
- try
- {
- connection.Open();
-
- SqlCommand cmd = new SqlCommand(sql, connection);
-
- foreach (SqlParameter cur_sp in sp)
- {
- if (cur_sp.Value != null)
- {
- cmd.Parameters.Add(cur_sp);
- }
- }
-
- return cmd.ExecuteNonQuery();
- }
- finally
- {
- connection.Close();
- }
- }
-
- ///
- /// 執行多條SQL語句,實現數據庫事物
- ///
- /// 多條SQL語句
- /// 請求數據庫類別
- /// 1 表示執行成功;2 表示出現錯誤了。
- public static void ExecuteSQLTran(List<string> SQLStringList, DBConnList DBConnIndex, ref int result)
- {
- var connstr = GetConnectStr(DBConnIndex);
-
- using (SqlConnection conn = new SqlConnection(connstr))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = conn;
- SqlTransaction tx = conn.BeginTransaction();
- cmd.Transaction = tx;
-
- int curIndex = 0;
-
- try
- {
- for (int n = 0; n < SQLStringList.Count; n++)
- {
- string strsql = SQLStringList[n].ToString();
- if (strsql.Trim().Length > 1)
- {
- cmd.CommandText = strsql;
- cmd.ExecuteNonQuery();
-
- curIndex = curIndex + 1;
- }
- }
- tx.Commit();
-
- result = 1;
- }
- catch (SqlException ex)
- {
- result = 2;
-
- Add_Log("ExecuteSqlTran:" + SQLStringList[curIndex] + " \r\n Error:" + ex.Message);
-
- tx.Rollback();
- //throw new Exception(E.Message);
- }
- }
- }
-
- ///
- /// 查詢
- ///
- /// 需要執行的SQL語句
- /// 請求數據庫類別
- ///
- public static DataTable SearchSQL(string sql, DBConnList DBConnIndex)
- {
- var connstr = GetConnectStr(DBConnIndex);
-
- DataSet ds = new DataSet();
-
- SqlDataAdapter sda = new SqlDataAdapter(sql, connstr);
-
- sda.Fill(ds);
-
- return ds.Tables[0];
- }
- public static DataTable Only_Table1(string exec, DBConnList DBConnIndex)
- {
- var connstr = GetConnectStr(DBConnIndex);
- System.Data.DataTable dt_jdl = new DataTable();
- try
- {
- using (SqlConnection con = new SqlConnection(connstr))
- {
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- } if (con.State == ConnectionState.Open || con.State == ConnectionState.Connecting)
- {
- SqlDataAdapter sda2 = new SqlDataAdapter(exec, con);//全部通過寫存儲過程即可
- DataSet ds2 = new DataSet();
- sda2.Fill(ds2, "cxq");
- dt_jdl = ds2.Tables["cxq"];
- sda2.Dispose();
- ds2.Dispose();
- }
- con.Close();
- }
- return dt_jdl;
- }
- catch (Exception EX)
- {
- return null;
- }
- }
-
- ///
- /// 增加日志
- ///
- ///
- public static void Add_Log(string msg)
- {
- //msg = msg.Replace("'", "");
-
- //StringBuilder sb = new StringBuilder();
-
- //sb.AppendLine("Insert into SimpHomeDB.dbo.SYS_LOG (msg)");
-
- //sb.AppendLine("Values(N'[SimploScreenAPI]" + msg + "')");
-
- //ExecuteSQL(sb.ToString(), DBConnList.DBConnStrTE);
- }
- #endregion
- //Qracle数据库操作
- #region
-
- ///
- /// 执行SQL语句,返回DataTable;只用来执行查询结果比较少的情况
- ///
- ///
- ///
- ///
- ///
- public static DataTable QracleExecuteDataTableSQL(string sql, DBConnList DBConnIndex,params OracleParameter[] parameters)
- {
- var connStr = GetConnectStr(DBConnIndex);
- using (OracleConnection conn = new OracleConnection(connStr))
- {
- conn.Open();
- using (OracleCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = sql;
- cmd.Parameters.AddRange(parameters);
- OracleDataAdapter adapter = new OracleDataAdapter(cmd);
- DataTable datatable = new DataTable();
- adapter.Fill(datatable);
- return datatable;
- }
- }
- }
- ///
- /// 执行SQl语句(增、删、改)
- ///
- /// 要执行的SQl语句
- ///
- public static bool Qracle_EXCUTE(string sql, DBConnList DBConnIndex)
- {
- var connStr = GetConnectStr(DBConnIndex);
- try
- {
- OracleConnection connect = new OracleConnection(connStr);
- OracleCommand cmd = new OracleCommand();
- cmd.Connection = connect;
- cmd.CommandText = sql;
- connect.Open();
- cmd.ExecuteNonQuery();
- connect.Close();
- return true;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- }
- #endregion
- }
- }
(6)Models文件下的类,例SysResponse类:
- ///
- /// 返回信息
- ///
- public class SysResponse
- {
- ///
- /// 状态码
- ///
- public string Code { get; set; }
-
- ///
- /// 描述信息
- ///
- public string Message { get; set; }
-
- ///
- /// 数据
- ///
- public object Data { get; set; }
-
-
- }
Common类
- public class Common
- {
- ///
- /// 轉化成Json
- ///
- /// 待轉換對象
- ///
轉換結果/returns> - public static HttpResponseMessage ToJson(Object obj)
- {
- String str;
- if (obj is String || obj is Char)
- {
- str = obj.ToString();
- }
- else
- {
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- str = serializer.Serialize(obj);
- }
- HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
-
- return result;
- }
- }
(7)接口类TestController
- public class TestController : ApiController
- {
- [HttpGet]
- public HttpResponseMessage HelloOne(string Line)
- {
- SysResponse res = new SysResponse();
- try
- {
- //sql数据库
- var emp_dt = SQLHelper.SearchSQL("select * from pcp where Line = '" + Line + "'", DBConnList.DBConnStr1);
- //Qracle数据库
- //var emp_dt = SQLHelper.QracleExecuteDataTableSQL("select * from (select * from scqhp.cell_sort_info_by_customer) where ROWNUM<=10 ORDER BY ROWNUM asc", DBConnList.QracleConnS);
-
- //var GoodsNo = emp_dt.Rows[0]["CELL_SN"].ToString();
- var GoodsNo = emp_dt.Rows[0]["P_N"].ToString();
- res.Code = "01";
- res.Message = GoodsNo;
- res.Data = "001";
- }
- catch (Exception ex)
- {
- res.Code = "02";
- res.Message = "調用失敗Hello,Exception:" + ex.Message + Line;
- res.Data = "002";
- }
-
- return Common.ToJson(res);
- }
-
-
- }
说明:其中 [HttpGet]可以按照需求更改为 [HttpPost] [HttpPut] [HttpDelete]
写好的接口需要发布到服务器或者本机的IIS进行测试,发布与发布网页一样
- html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <script src="jquery-1.10.2.min.js">script>
- <style>
-
- style>
- <title>webapi测试title>
- head>
- <body>
- <div id="body">
- <section>
-
- <br />
- <br />
- <h2>查询物料h2>
- Line:<input id="line" type="text" value="PZ01"/><br />
- 料号:<input id="GoodsNo" type="text" /><br />
- <input id="showItem" type="button" value="查询" />
- section>
-
- div>
-
- <script>
- //先根据Id查询记录 请求类型:GET 请求url: /api/Products/Id
- //请求到ProductsController.cs中的 public Product GetProduct(int id) 方法
- $("#showItem").click(function () {
- var inputLine = $("#line").val();
- $.ajax({
- url: "http://10.20.32.73:8000//api/Test/HelloOne?Line=" + inputLine,
- type: "get",
- dataType: 'json',
- success: function (data) {
- $("#GoodsNo").val(data.Message);
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- alert("请求失败,消息:" + textStatus + " " + errorThrown);
- }
- });
- });
- script>
-
- body>
- html>
说明:其中http://10.20.32.73:8000为发布webAPI的网址
总结:本文主要讲述了WebAPI项目的搭建及其配置,然后到发布及其测试整个过程。记录方便查阅。