ASP.NET MVC API 接口验证的示例代码
项目的开发通常依赖于我们建站初期的框架,而依赖注入不仅在ASP.NET核心本身提供服务,今天爱站技术频道小编就给朋友们详细ASP.NET MVC API 接口验证的示例代码,仅供大家参考。
1、WebApiConfig全局处理
///
public static class WebApiConfig { ///
/// public static void Register(HttpConfiguration config) { // Web API configuration and services //强制https访问 //config.Filters.Add(new ForceHttpsAttribute()); // 统一回传格式 config.Filters.Add(new ApiResultAttribute()); // 发生异常时处理 config.Filters.Add(new ApiErrorHandleAttribute()); // ToKen身份验证过滤器 更方便 不需要在这里了 具有改标签的就会自动检查 //config.Filters.Add(new ApiAuthFilterAttribute()); // 解决json序列化时的循环引用问题 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //对日期格式进行统一处理 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add( new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" } ); // Web API routes 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); // 干掉XML序列化器 //config.Formatters.Remove(config.Formatters.XmlFormatter); //在请求的Url加上 ?$format=xml,便可以指定响应格式 config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json"); } }
2、身份验证过滤器
using DotNet.Business; using DotNet.Utilities; using DotNet.Tracking.API.Common; ///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class ApiAuthFilterAttribute : AuthorizationFilterAttribute { ///
private const string UnauthorizedMessage = "请求未授权,拒绝访问。"; ///
/// public override void OnAuthorization(HttpActionContext actionContext) { base.OnAuthorization(actionContext); // 允许匿名访问 if (actionContext.ActionDescriptor.GetCustomAttributes
Unauthorized
", Encoding.UTF8, "text/html"); var response = actionContext.Response= actionContext.Response?? new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Unauthorized; BaseResult result = new BaseResult { Status = false, StatusMessage = UnauthorizedMessage }; response.Content = new StringContent(result.ToJson(), Encoding.UTF8, "application/json"); } else { // 检查 AppKey 和 AppSecret BaseResult result = BaseServicesLicenseManager.CheckService(appKey, appSecret, false, 0, 0, systemCode, permissionCode); if (!result.Status) { var response = actionContext.Response = actionContext.Response?? new HttpResponseMessage(); response.Content = new StringContent(result.ToJson(), Encoding.UTF8, "application/json"); } } } }
3、统一回传格式
///
public class ApiResultAttribute : ActionFilterAttribute { ///
/// public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { // 快件跟踪接口传的是format,不用走这里 if (actionExecutedContext.Request.Properties.ContainsKey("format")) { // 若发生例外则不在这边处理 在异常中处理 ApiErrorHandleAttribute if (actionExecutedContext.Exception != null) return; base.OnActionExecuted(actionExecutedContext); var result = new ApiResultModel(); // 取得由 API 返回的状态码 result.Status = actionExecutedContext.ActionContext.Response.StatusCode; // 取得由 API 返回的资料 result.Data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync
4、全局异常处理
using DotNet.Utilities; using DotNet.Tracking.API.Common; using DotNet.Tracking.API.Controllers; using DotNet.Tracking.API.Models; ///
public class ApiErrorHandleAttribute : System.Web.Http.Filters.ExceptionFilterAttribute { ///
/// public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) { base.OnException(actionExecutedContext); // 取得发生例外时的错误讯息 var errorMessage = actionExecutedContext.Exception.Message; // 异常记录 string parameters = APIOperateContext.GetRequestParameters(); NLogHelper.Trace(actionExecutedContext.Exception, BaseSystemInfo.SystemCode + " ApiErrorHandleAttribute OnException 完整的请求地址及参数 : " + parameters); // 2016-11-01 加入异常邮件提醒 NLogHelper.InfoMail(actionExecutedContext.Exception, BaseSystemInfo.SystemCode + " ApiErrorHandleAttribute OnException 完整的请求地址及参数 : " + parameters); var result = new ApiResultModel() { Status = HttpStatusCode.BadRequest, ErrorMessage = errorMessage }; // 重新打包回传的讯息 actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result.Status, result); } }
5、接口操作的上下文
using DotNet.Business; using DotNet.Model; using DotNet.Utilities; ///
public class APIOperateContext { ///
public static APIOperateContext Current { get { APIOperateContext oContext = CallContext.GetData(typeof(APIOperateContext).Name) as APIOperateContext; if (oContext == null) { oContext = new APIOperateContext(); CallContext.SetData(typeof(APIOperateContext).Name, oContext); } return oContext; } } #region Http上下文 及 相关属性 ///
public HttpContext ContextHttp { get { return HttpContext.Current; } } ///
public HttpResponse Response { get { return ContextHttp.Response; } } ///
public HttpRequest Request { get { return ContextHttp.Request; } } ///
System.Web.SessionState.HttpSessionState Session { get { return ContextHttp.Session; } } #endregion ///
public static string GetRequestParameters() { string query = HttpContext.Current.Request.Url.Query; NameValueCollection nvc; string baseUrl; ParseUrl(query, out baseUrl, out nvc); List
///输入的 URL ///输出 URL 的基础部分 ///输出分析后得到的 (参数名,参数值) 的集合 public static void ParseUrl(string url, out string baseUrl, out NameValueCollection nvc) { if (url == null) { throw new ArgumentNullException("url"); } nvc = new NameValueCollection(); baseUrl = ""; if (url == "") { return; } int questionMarkIndex = url.IndexOf('?'); if (questionMarkIndex == -1) { baseUrl = url; return; } baseUrl = url.Substring(0, questionMarkIndex); if (questionMarkIndex == url.Length - 1) { return; } string ps = url.Substring(questionMarkIndex + 1); // 开始分析参数对 Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled); MatchCollection mc = re.Matches(ps); foreach (Match m in mc) { nvc.Add(m.Result("$2").ToLower(), m.Result("$3")); } } ///
public string SystemCode { get { return Request["systemCode"] ?? "Base"; } } ///
public string PermissionCode { get { return Request["permissionCode"]; } } ///
public string AppKey { get { return Request["appKey"]; } } ///
public string AppSecret { get { return Request["appSecret"]; } } private BaseUserInfo _userInfo = null; ///
///
public static IDbHelper BusinessDbHelper { get { return DbHelperFactory.GetHelper(BaseSystemInfo.BusinessDbType, BaseSystemInfo.BusinessDbConnection); } } #endregion #region 用户中心库连接 ///
public static IDbHelper UserCenterDbHelper { get { return DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection); } } #endregion }
7、统一回传格式实体
///
public class ApiResultModel { public HttpStatusCode Status { get; set; } //public JsonResult
8、留言相关接口
///
[ApiAuthFilter] public class CustomerMessageController : ApiController { ///
/// ///
/// /// > jsonResult = new JsonResult
>(); try { MsgbookCusManager manager = new MsgbookCusManager(APIOperateContext.BusinessDbHelper, APIOperateContext.Current.UserInfo); List
9、接口调用方法
///
///
以上就是爱站技术频道小编给大家介绍的ASP.NET MVC API 接口验证的示例代码,我们要记得操作步骤和操作要领哦。