There is a message message interface in the project that receives messages and displays messages from other systems. I refer to some API verification methods on the Internet and found that the verification methods provided by the general permission management system are the most perfect.
The complete idea shared below
1. WebApiConfig global processing
/// <summary> /// WebApiConfig /// Basic routing configuration. /// /// /// Modify records /// /// 2016.11.01 Version: 2.0 Song Biao uniformly handles the date format. /// 2016.10.30 Version: 2.0 Song Biao Solve the problem of circular reference during json serialization. /// 2016.10.28 Version: 2.0 Song Biao Back-pass response format $format supports. /// 2016.09.01 Version: 1.0 Song Biao Created. /// /// Version: 1.0 /// /// <author> /// <name>Song Biao</name> /// <date>2016.09.01</date> /// </author> /// </summary> public static class WebApiConfig { /// <summary> /// Register global configuration service /// </summary> /// <param name="config"></param> public static void Register(HttpConfiguration config) { // Web API configuration and services //Forced https access //(new ForceHttpsAttribute()); // Unified return format (new ApiResultAttribute()); // Handle when an exception occurs (new ApiErrorHandleAttribute()); // ToKen authentication filter is more convenient. No need to be here. Those with changed tags will automatically check //(new ApiAuthFilterAttribute()); // Solve the problem of circular reference during json serialization = ; //Use unified processing of date format ( new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" } ); // Web API routes routes (); ( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = } ); // Kill the XML serializer //(); // Add ?$format=xml to the requested URL to specify the response format ("$format", "xml", "application/xml"); ("$format", "json", "application/json"); } }
2. Authentication filter
using ; using ; using ; /// <summary> /// ApiAuthFilterAttribute /// Authentication filter, methods with ApiAuthFilterAttribute tag attribute will automatically check /// /// /// Modify the record /// /// 2016-10-11 Version: 1.0 SongBiao Create file. /// /// <author> /// <name>SongBiao</name> /// <date>2016-10-11</date> /// </author> /// </summary> [AttributeUsage( | , Inherited = true, AllowMultiple = true)] public class ApiAuthFilterAttribute : AuthorizationFilterAttribute { /// <summary> /// Prompt message when unauthorized /// </summary> private const string UnauthorizedMessage = "The request is not authorized, access is denied."; /// <summary> ///Enter permissions /// </summary> /// <param name="actionContext"></param> public override void OnAuthorization(HttpActionContext actionContext) { (actionContext); // Allow anonymous access if (<AllowAnonymousAttribute>().Count > 0) { return; } string systemCode = ; string permissionCode = ; string appKey = ; string appSecret = ; if ((appKey) || (appSecret)) { //Users who are not verified (login) and are not anonymously accessed, then turn to the login page // = (); // = new StringContent("<p>Unauthorized</p>", Encoding.UTF8, "text/html"); var response = = ?? new HttpResponseMessage(); = ; BaseResult result = new BaseResult { Status = false, StatusMessage = UnauthorizedMessage }; = new StringContent((), Encoding.UTF8, "application/json"); } else { // Check AppKey and AppSecret BaseResult result = (appKey, appSecret, false, 0, 0, systemCode, permissionCode); if (!) { var response = = ?? new HttpResponseMessage(); = new StringContent((), Encoding.UTF8, "application/json"); } } } }
3. Unified return format
/// <summary> /// ApiResultAttribute /// Unified return format /// /// Modify the record /// /// 2016-10-31 Version: 1.0 Song Biao Creates the file. /// /// <author> /// <name>Song Biao</name> /// <date>2016-10-31</date> /// </author> /// </summary> public class ApiResultAttribute : ActionFilterAttribute { /// <summary> /// Rewrite the process of returning the pass /// </summary> /// <param name="actionExecutedContext"></param> public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { // The express tracking interface transmits format, you don't need to go here if (("format")) { // If an exception occurs, it will not be handled here. Processed in the exception. ApiErrorHandleAttribute if ( != null) return; (actionExecutedContext); var result = new ApiResultModel(); // Get the status code returned by the API = ; // Get the information returned by the API = <object>().Result; // Re-encapsulate the return format = (, result); } } }
4. Global exception handling
using ; using ; using ; using ; /// <summary> /// ApiErrorHandleAttribute /// Global exception handling /// /// Modify the record /// /// 2016-10-31 Version: 1.0 Song Biao Creates the file. /// /// <author> /// <name>Song Biao</name> /// <date>2016-10-31</date> /// </author> /// </summary> public class ApiErrorHandleAttribute : { /// <summary> /// Unified exception handling /// </summary> /// <param name="actionExecutedContext"></param> public override void OnException( actionExecutedContext) { (actionExecutedContext); // Get the error message when an exception occurs var errorMessage = ; // Exception logging string parameters = (); (, + " ApiErrorHandleAttribute OnException Complete request address and parameters: " + parameters); // 2016-11-01 Add an exception email reminder (, + " ApiErrorHandleAttribute OnException Complete request address and parameters: " + parameters); var result = new ApiResultModel() { Status = , ErrorMessage = errorMessage }; // Repackage the message back = (, result); } }
5. The context of interface operation
using ; using ; using ; /// <summary> /// APIOperateContext /// Context of interface operation /// Some common things related to the context are placed here to deal with /// /// Modify the record /// /// 2016-10-31 Version: 1.0 Song Biao Creates the file. /// /// <author> /// <name>Song Biao</name> /// <date>2016-10-31</date> /// </author> /// </summary> public class APIOperateContext { /// <summary> /// Get the current operation context (create the operation context separately for each server thread that handles the browser request) /// </summary> public static APIOperateContext Current { get { APIOperateContext oContext = (typeof(APIOperateContext).Name) as APIOperateContext; if (oContext == null) { oContext = new APIOperateContext(); (typeof(APIOperateContext).Name, oContext); } return oContext; } } #region Http context and related properties /// <summary> /// Http context /// </summary> public HttpContext ContextHttp { get { return ; } } /// <summary> /// Output object /// </summary> public HttpResponse Response { get { return ; } } /// <summary> /// Request object /// </summary> public HttpRequest Request { get { return ; } } /// <summary> /// Session object /// </summary> Session { get { return ; } } #endregion /// <summary> /// Get all request parameters, simplified versions of get and post /// </summary> public static string GetRequestParameters() { string query = ; NameValueCollection nvc; string baseUrl; ParseUrl(query, out baseUrl, out nvc); List<string> list = new List<string>() { }; foreach (var key in ) { (key + "=" + nvc[key]); } var form = ; foreach (var key in ) { (key + "=" + form[key]); } string result = + "?" + ("&", list); return result; } /// <summary> /// Analyze parameter information in the url string /// For get request /// </summary> /// <param name="url">Entered URL</param> /// <param name="baseUrl">Output basic part of URL</param> /// <param name="nvc">Set of (parameter name, parameter value) obtained after output analysis</param> 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 = ('?'); if (questionMarkIndex == -1) { baseUrl = url; return; } baseUrl = (0, questionMarkIndex); if (questionMarkIndex == - 1) { return; } string ps = (questionMarkIndex + 1); // Start analyzing parameter pairs Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", ); MatchCollection mc = (ps); foreach (Match m in mc) { (("$2").ToLower(), ("$3")); } } /// <summary> /// System number /// </summary> public string SystemCode { get { return Request["systemCode"] ?? "Base"; } } /// <summary> /// Permission number /// </summary> public string PermissionCode { get { return Request["permissionCode"]; } } /// <summary> /// AppKey is sent to the interface /// </summary> public string AppKey { get { return Request["appKey"]; } } /// <summary> /// AppSecret is sent to the interface /// </summary> public string AppSecret { get { return Request["appSecret"]; } } private BaseUserInfo _userInfo = null; /// <summary> /// Get the current user /// Users obtained through the interfaces AppKey and AppSecret /// </summary> /// <returns></returns> public BaseUserInfo UserInfo { get { BaseUserInfo userInfo = null; BaseUserEntity userEntity = (AppKey); if (userEntity != null) { if ((, AppSecret)) { userInfo = new BaseUserInfo(); = ; = ; = ; = (true); } } return userInfo; } } #region Business Library Connection /// <summary> /// Business library connection /// </summary> public static IDbHelper BusinessDbHelper { get { return (, ); } } #endregion #region User Center Library Connection /// <summary> /// User Center Library Connection /// </summary> public static IDbHelper UserCenterDbHelper { get { return (, ); } } #endregion }
7. Unified return format entity
/// <summary> /// ApiResultModel /// Unified return format entity /// /// Modify the record /// /// 2016-10-31 Version: 1.0 Song Biao Creates the file. /// /// <author> /// <name>Song Biao</name> /// <date>2016-10-31</date> /// </author> /// </summary> public class ApiResultModel { public HttpStatusCode Status { get; set; } //public JsonResult<T> Data { get; set; } public object Data { get; set; } public string ErrorMessage { get; set; } }
8. Message-related interface
/// <summary> /// MessageBookController /// Message-related interface /// /// Modify the record /// /// 2016-10-31 Version: 1.0 Song Biao Creates the file. /// /// <author> /// <name>Song Biao</name> /// <date>2016-10-31</date> /// </author> /// </summary> [ApiAuthFilter] public class CustomerMessageController : ApiController { /// <summary> /// Save the message information of the order number /// </summary> /// <param name="messageBook"></param> /// <returns></returns> [HttpPost] //[AllowAnonymous] Add this tag if you don't need verification public IHttpActionResult Add([FromBody]MsgbookCusEntity messageBook) { BaseResult baseResult = new BaseResult(); if (()) { = false; = "SystemFrom parameter cannot be empty"; } else { try { MsgbookCusManager manager = new MsgbookCusManager(, ); MsgbookCusEntity model = new MsgbookCusEntity(); = ().ToString("N"); = ; = ; = ; = ; = ; = ; = 0; (model, false, false); = true; = "Added successfully."; } catch (Exception ex) { (ex, "CustomerMessageController AddBillMessage Exception"); = false; = "abnormal:" + ; } } return Ok(baseResult); } /// <summary> /// Get a message for a certain order number /// </summary> /// <param name="billCode"></param> /// <returns></returns> [HttpGet] public IHttpActionResult GetList(string billCode) { JsonResult<List<MsgbookCusEntity>> jsonResult = new JsonResult<List<MsgbookCusEntity>>(); try { MsgbookCusManager manager = new MsgbookCusManager(, ); List<MsgbookCusEntity> list = new List<MsgbookCusEntity>(); list = <MsgbookCusEntity>(new KeyValuePair<string, object>(, billCode) , new KeyValuePair<string, object>(, 0)); = true; = ; = list; = "Get Successful"; } catch (Exception ex) { (ex, "CustomerMessageController AddBillMessage Exception"); = false; = "abnormal:" + ; } return Ok(jsonResult); } }
9. Interface call method
/// <summary> /// Test message interface call /// </summary> /// <returns></returns> public ActionResult AddCustomerMessage() { string url = "http://192.168.1.88:808/api/CustomerMessage/Add?"; WebClient webClient = new WebClient(); NameValueCollection postValues = new NameValueCollection(); ("Message", "Fill in your message content"); ("SendEmail", "youemail@"); ("SendTelephone", "021-60375335"); ("Code", "661137858"); ("AppKey", "wssavbcn"); ("AppSecret", "350e66b1e6564b0a817163erwwwwe8"); ("SystemFrom", "Official Website"); byte[] responseArray = (url, postValues); string response = Encoding.(responseArray); return Content(response); }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.