个人笔记,记录Nancy异步用法

基类,所有请求都将首先执行该类,并执行Before事件
namespace CxyAdvert.Base
{
public class BaseNancyModel : Nancy.NancyModule
{
public BaseNancyModel()
{
Get["/"] = param =>
{
return "ADVERT SYSTEM";
};
}
public BaseNancyModel(string path)
: base(path)
{
Before += async (context, token) =>
{
return await VerifyAuth(context);
}; //After += async (context, token) =>
//{
// await VerifyAuth(context);
//};
}      /// <summary>
/// Before执行的函数,返回null将继续执行路由指定接口,返回Response将结束并返回
/// </summary>
/// <param name="nancyContext"></param>
/// <returns></returns>
private async Task<Response> VerifyAuth(Nancy.NancyContext nancyContext)
{
try
{
var httpMethod = nancyContext.Request.Method;
if (httpMethod.ToUpper() == "POST")
{
var requestParms = HttpHelper.GetPostValue(nancyContext.Request.Body);
if (requestParms == "")
{
return Response.AsJson(new ResultMsg() { code = -, errormsg = "参数值不能为空" });
}
else
{ }
}
return null;
}
catch (Exception error)
{
Logger.Error("BaseNancyModel ERROR:" + error);
return Response.AsJson(new ResultMsg() { code = -, errormsg = error.Message });
}
}      public object GetEncryptValue(object msg)
{
var strJson = JsonConvert.SerializeObject(msg, StringFormat.jsonSerializerSettings);
return strJson ;
}
}
}
接口类,所有接口类继承基类BaseNancyModel,GetEncryptValue函数实现于基类BaseNancyModel中
namespace CxyAdvert
{
public class AdvertSericeApi : BaseNancyModel
{
public AdvertSericeApi() :
base("/cxy/api/advert/")
{
IAdvertSerice service = new AdvertSerice(); Post["getshowadverts", true] = async (param, token) =>
{
return GetEncryptValue(await service.GetShowAdverts(BaseInputParam, ThridUser));
}; Post["getadverts", true] = async (param, token) =>
{
return GetEncryptValue(await service.GetAdverts(BaseInputParam, ThridUser));
};
}
}
}
04-25 22:55