目录
1.创建项目
2.配置
3.发布
4.测试页面
1.创建项目
(1)创建ASP.NET Web应用程式,如下图:
(2)选择Empty,勾选Web API,点击确定创建,如下图:
(3)创建完成,如下图:
(4)添加文件夹及类,如下图:
说明:BLL(存放数据库相关的类),TestController(接口类),Models(存放Models类),MPage(存放啟動頁面,沒有任何功能)
2.配置
(1)Web.config配置文件,配置数据库连接及跨域,代码如下:
<configuration>
<appSettings>
<!--配置数据库连接-->
<!--数据库1-->
<add key="DBConnectionString1" value="Data Source=1.3.1.1;Initial Catalog=total;Persist Security Info=True;User ID=SC;Password=SCQSMPTD;MultipleActiveResultSets=true" />
<!--数据库2-->
<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" />
<!--数据库3-->
<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;"/>
</appSettings>
<httpProtocol>
<!--跨域配置开始-->
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<!--支持全域名访问,不安全,部署后需要固定限制为客户端网址-->
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<!--支持的http 动作-->
<add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With,token,staffid,timestamp,nonce,signKey,signature" />
<!--响应头 请按照自己需求添加 这里新加了token这个headers-->
<add name="Access-Control-Request-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<!--允许请求的http 动作-->
</customHeaders>
<!--跨域配置结束-->
</httpProtocol>
</system.webServer>
</configuration>
(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" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
這個界面只是一個啟動頁面,沒有任何功能
</div>
</form>
</body>
</html>
(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
{
/// <summary>
/// 鏈接類別
/// </summary>
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"];
/// <summary>
/// 獲得數據庫鏈接語句
/// </summary>
/// <param name="DBConnIndex">請求數據庫類別</param>
/// <returns></returns>
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
/// <summary>
/// 增刪改查,不涉及事物
/// </summary>
/// <param name="sql"></param>
/// <param name="DBConnIndex">請求數據庫類別</param>
/// <returns></returns>
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;
}
/// <summary>
/// 执行带SqlParameter的SQL语句
/// </summary>
/// <param name="sql"></param>
/// <param name="DBConnIndex">請求數據庫類別</param>
/// <param name="sp">參數</param>
/// <returns></returns>
public static int ExecuteSQLAndSP(string sql, DBConnList DBConnIndex, List<SqlParameter> 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();
}
}
/// <summary>
/// 執行多條SQL語句,實現數據庫事物
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
/// <param name="DBConnIndex">請求數據庫類別</param>
/// <param name="result">1 表示執行成功;2 表示出現錯誤了。</param>
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);
}
}
}
/// <summary>
/// 查詢
/// </summary>
/// <param name="sql">需要執行的SQL語句</param>
/// <param name="DBConnIndex">請求數據庫類別</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 增加日志
/// </summary>
/// <param name="msg"></param>
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
/// <summary>
/// 执行SQL语句,返回DataTable;只用来执行查询结果比较少的情况
/// </summary>
/// <param name="sql"></param>
/// <param name="DBConnIndex"></param>
/// <param name="parameters"></param>
/// <returns></returns>
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;
}
}
}
/// <summary>
/// 执行SQl语句(增、删、改)
/// </summary>
/// <param name="sql">要执行的SQl语句</param>
/// <returns></returns>
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类:
/// <summary>
/// 返回信息
/// </summary>
public class SysResponse
{
/// <summary>
/// 状态码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 描述信息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 数据
/// </summary>
public object Data { get; set; }
}
Common类
public class Common
{
/// <summary>
/// 轉化成Json
/// </summary>
/// <param name="obj">待轉換對象</param>
/// <returns>轉換結果/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]
3.发布
写好的接口需要发布到服务器或者本机的IIS进行测试,发布与发布网页一样
4.测试页面
<!DOCTYPE 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项目的搭建及其配置,然后到发布及其测试整个过程。记录方便查阅。