開發Web Api的接口在windows服務中實現,需要先安裝4個組件,分別如下:
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.SelfHost" version="5.2.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
我是用vs2015的開發工具來做此件事情的,先上項目結構圖:
圖1
先分別講一下,各個項目的職能
第一、YBaseFramework.YBF.WebApiEngine 此項目是具體實現 WebApi的引擎,我會借一個工具來實,具體代碼如下:
/// <summary>
/// 開始啟動服務
/// </summary>
/// <returns></returns>
public bool Start()
{
_context.Info("執行啟動");
_context.DebugFormat(GetType(), "WebApiEngine {0} Starting... ", Utils.GetVersion());
try
{
var config = new HttpSelfHostConfiguration(BaseConfig.Hosts);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("YBF.WebApiServiceController.exe.config");
XmlNodeList nodes = xmlDocument.SelectNodes("configuration/preLoadedAssemblies/add");
foreach (XmlNode n in nodes)
{
string dllname = n.Attributes["assemblyName"].InnerText.Trim();//其它屬性類似獲取 這里輸出Conn
string localhostdll = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + dllname;
string projectCode = BaseConfig.GetDllProCode(dllname);//項目縮寫代碼
Assembly dllFile = Assembly.UnsafeLoadFrom(localhostdll);
Type[] classType = dllFile.GetTypes();
foreach (var item in classType)
{
if (item.FullName.ToLower().IndexOf("dbservices") > 0)
{
string[] nameSpaceNames = item.FullName.Split('.');
string module = nameSpaceNames[2].ToLower().Replace("dbservices", "");//模塊名稱
string nameSpaceName = nameSpaceNames[0] + "." + nameSpaceNames[1] + "." + nameSpaceNames[2];
config.Routes.MapHttpRoute(
projectCode + module, projectCode + "/" + module + "/{controller}/{action}" + BaseConfig.Suffix,
new
{
action = RouteParameter.Optional,
id = RouteParameter.Optional,
namespaceName = new string[1] { nameSpaceName }
});
}
}
}
server = new HttpSelfHostServer(config);
server.Configuration.Services.Replace(typeof(IAssembliesResolver), new ExtendedDefaultAssembliesResolver());
server.OpenAsync().Wait();
server.Configuration.Services.Replace(typeof(IHttpControllerSelector),
new NamespaceHttpControllerSelector(server.Configuration));
if (BaseConfig.OutputformatIsJson)
{
#region 接口返回結果格式
var jsonFormatter = new JsonMediaTypeFormatter();
server.Configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
#endregion 接口返回結果格式
}
_context.Info("WebApi服務已開啟,已成功監控!");
return true;
}
catch (Exception ex)
{
server.CloseAsync().Wait();
server.Dispose();
_context.ErrorFormat(GetType(), "WebApi服務已失敗,原因{0}!",ex.Message);
return false;
}
}
BaseSetting的文件夾為一些基礎配置與實現,如動態加載dll文件等;
Helper的文件夾為接中返回結果的類型定義類;
第二、YBaseFramework.YBF.PublicConfig 此項目為公共信息配置,有兩個文件夾要注意:
Helper文件夾中的ConstHelper類是一些常量的定義,ParamVerificationHelper類是表單參數的驗證;
RestResult文件夾接口返回的類;
圖2
public class Response
{
public int status { get; set; }
public string msg { get; set; }
public object data { get; set; }
}
public class PageData
{
public int totalnum { get; set; }
public int totalpage { get; set; }
public int currentpage { get; set; }
public object info { get; set; }
}
第三、YBaseFramework.YBF.HelloWorldApiServices此項目為WebApi具體實現,目前HelloWorld為名,僅是一個demo,文件結構如下:
圖3
在上面的引擎中,我已經將路由的定義,標紅色文字,所以這里的DemoDBServices的文件夾的命名就是必須以DBServices結束,控制器的命令也是以Controller結束,只好mvc中的控制器命名一樣;
[HttpGet]
public Response GetUsers()
{
try
{
var res = new Response();
res.status = 0;
res.msg = "success";
var data = new PageData();
data.currentpage = 1;
data.totalnum = 100;
data.totalpage = 10;
var infos = new List<dynamic>();
for (int i = 1; i < 1000; i++)
{
infos.Add(new { Name = "abc" + i.ToString(), ID = i });
}
data.info = infos;
res.data = data;
_context.InfoFormat(GetType(), "HelloWorldController {0} 處理數據條數:{1}", Utils.GetVersion(), infos.Count);
return res;
}
catch (Exception ex)
{
_context.ErrorFormat(GetType(), "HelloWorldController {0} 錯誤原因:{1}", Utils.GetVersion(),ex.Message);
return null;
}
}
/// <summary>
/// post測試驗證登錄
/// </summary>
/// <param name="memberModel"></param>
/// <returns></returns>
[HttpPost]
public Response LoginCheck([FromBody]MEMBERModel memberModel)
{
var obj = RequestContext.RouteData.Values;//取路由的信息
string Url = RequestContext.Url.Request.RequestUri.LocalPath;
Response res = ParamVerificationHelper.CheckParVerLegal<MEMBERModel>(Url, memberModel);
if (res != null)
{
return res;
}
string msg = string.Empty;
string state = "0";
if(string.IsNullOrWhiteSpace(memberModel.USERNAME))
{
state = "3";
}
else if(string.IsNullOrWhiteSpace(memberModel.PASSWORD))
{
state = "2";
}
switch (state)
{
case "0":
msg = "登錄成功";
break;
case "1":
msg = "審核不通過";
break;
case "2":
msg = "密碼不正確";
break;
case "3":
msg = "帳號不存在";
break;
}
object data = null;
if (state == "0")
{
data =
new
{
username = memberModel.USERNAME,
phone = "13761085465-app",
email = "baishi_12@163.com",
image =
string.IsNullOrEmpty("")
? "http://www.gjw.com/image/face/1.jpg"
: "http://img0.gjw.com/face/" + "",
name = "baishi",
gender = "男" == "女" ? "2" : "1",
password = ""
};
}
var response = new Response { status = state == "0" ? 0 : 1, msg = msg, data = data };
return response;
}
在DemoModel文件夾中是定義了具體接口所要使用到的實體:
ParamModel.cs為接口接收參數部分
/// <summary>
/// 前台會員信息
/// </summary>
public class MEMBERModel
{
public string USERNAME { get; set; }
public string PASSWORD { get; set; }
public string vastr { get; set; }
}
/// <summary>
/// 商品信息
/// </summary>
public class PRODUCTModel
{
public string vastr { get; set; }
}
Product.cs
public class Product
{
public string Name { get; set; }
public string Price { get; set; }
}
以上三個大步,就可以實現了兩個接口,下面我們就以Demo的操作圖片說明。
第四、發布測試接口
A、接口測試配置文件:
<root>
<Interface name="GetUsers" url="http://localhost:3721/hw/demo/HelloWorld/getusers.html" params="" type="get" remark="取用戶列表接口說明"></Interface>
<Interface name="Getlist" url="http://localhost:3721/hw/demo/HelloWorld/getlist.html" params="" type="get" remark="商品列表接口說明"></Interface>
<Interface name="LoginCheck" url="http://localhost:3721/hw/demo/HelloWorld/LoginCheck1.html" params="USERNAME={0}&PASSWORD={1}" type="post" remark="登錄接口說明"></Interface>
</root>
B、接口實體實現宿主程序,如圖:
圖4
C、測試接口結果
圖5
圖6
到此一個web api接口的實現與測試示例,已經完成了,實驗Demo會提供下載可以自己去測試;
WebAPI示例: 下載
后續還是講wcf restful的windows服務之路。