Sample Code for ASP. net mvc api Interface Verification, mvcapi
There is a message interface in the project, which receives messages and displays messages from other systems. According to some API verification methods on the Internet, it is found that the verification method provided by the general permission management system is the most perfect.
The following describes how to share the entire idea.
1. WebApiConfig global Processing
/// <Summary> /// WebApiConfig /// basic routing configuration. //////// Modify the record ///// 2016.11.01 version: 2.0 song Biao unifies the date format. /// 2016.10.30 version: 2.0 song Biao solves the issue of loop reference during json serialization. /// 2016.10.28 version: 2.0 $. /// 2016.09.01 version: 1.0 created by Song Biao. ///// Version: 1.0 ///// <author> /// <name> song Biao </name> /// <date> 2016.09.01 </date> /// </author> /// </summary> public static class WebApiConfig {// <summary> /// register the global configuration service /// </summary> /// <param name =" config "> </param> public static void Register (HttpConfiguration config) {// Web API configuration and services // force https access // config. filters. add (new ForceHttpsAttribute (); // unified callback format config. filters. Add (new ApiResultAttribute (); // process config when an exception occurs. filters. add (new ApiErrorHandleAttribute (); // The ToKen Authentication filter is more convenient. If you do not need to modify the tag here, the filter will automatically check // config. filters. add (new ApiAuthFilterAttribute (); // solve the circular reference problem during json serialization config. formatters. jsonFormatter. serializerSettings. referenceLoopHandling = Newtonsoft. json. referenceLoopHandling. ignore; // process the date format in a unified manner. config. formatters. jsonFormatter. serializerSettings. convert Ers. add (new IsoDateTimeConverter () {DateTimeFormat = "yyyy-MM-dd hh: mm: ss"}); // Web API routes route config. mapHttpAttributeRoutes (); config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new {id = RouteParameter. optional}); // get rid of the XML serializer // config. formatters. remove (config. formatters. xmlFormatter); // Add? $ Format = xml, you can specify the response format config. formatters. xmlFormatter. addQueryStringMapping ("$ format", "xml", "application/xml"); config. formatters. jsonFormatter. addQueryStringMapping ("$ format", "json", "application/json ");}}
2. authentication filter
Using DotNet. business; using DotNet. utilities; using DotNet. tracking. API. common; /// <summary> /// ApiAuthFilterAttribute /// authentication filter, the method that has the attributes of the ApiAuthFilterAttribute label will automatically check the // modify the record // 2016-10-11 version: 1.0 SongBiao to create a file. ///// <Author> /// <name> SongBiao </name> /// <date> 2016-10-11 </date> /// </author> // /</summary> [AttributeUsage (AttributeTargets. class | AttributeTargets. method, Inherited = true, AllowMultiple = true)] public class ApiAuthFilterAttribute: authorizationFilterAttribute {// <summary> /// prompt message when authorization is not performed /// </summary> private const string UnauthorizedMessage = "the request is not authorized and access is denied. "; /// <Summary> // enter the permission /// </summary> /// <param name = "actionContext"> </param> public override void OnAuthorization (HttpActionContext actionContext) {base. onAuthorization (actionContext); // allows anonymous access to if (actionContext. actionDescriptor. getCustomAttributes <AllowAnonymousAttribute> (). count> 0) {return;} string systemCode = APIOperateContext. current. systemCode; string permissionCode = APIOperateCon Text. current. permissionCode; string appKey = APIOperateContext. current. appKey; string appSecret = APIOperateContext. current. appSecret; if (string. isNullOrWhiteSpace (appKey) | string. isNullOrWhiteSpace (appSecret) {// unauthenticated (LOGIN) user, and non-Anonymous Access, go to the login page // actionContext. response = actionContext. request. createResponse (HttpStatusCode. unauthorized); // actionContext. response. content = new StringContent ("<p> Un Authorized </p> ", 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 {// check AppKey and AppSecret BaseResult result = BaseServicesLicenseManager. checkService (appKey, appSecret, false, 0, 0, systemCode, pe RmissionCode); if (! Result. Status) {var response = actionContext. Response = actionContext. Response ?? New HttpResponseMessage (); response. Content = new StringContent (result. ToJson (), Encoding. UTF8, "application/json ");}}}}
3. Unified return format
/// <Summary> /// ApiResultAttribute /// unified return format ///// modify the record ///// 2016-10-31 version: 1.0 create a file. ///// <Author> /// <name> song Biao </name> /// <date> </date> /// </author>/ // </summary> public class ApiResultAttribute: actionFilterAttribute {/// <summary> /// rewrite the processing of callback /// </summary> /// <param name = "actionExecutedContext"> </param> public override void onActionExecuted (HttpActionExecutedContext actionExecutedContext) {// The parcel tracking interface transmits the format. if (actionExecutedContext. request. properties. ContainsKey ("format") {// if an Exception occurs, it is not handled here. In the Exception, ApiErrorHandleAttribute if (actionExecutedContext. Exception! = Null) return; base. onActionExecuted (actionExecutedContext); var result = new ApiResultModel (); // gets the status code result returned by the API. status = actionExecutedContext. actionContext. response. statusCode; // obtain the result returned by the API. data = actionExecutedContext. actionContext. response. content. readAsAsync <object> (). result; // re-encapsulate the return format actionExecutedContext. response = actionExecutedContext. request. createResponse (result. status, result );}}}
4. Global Exception Handling
Using DotNet. utilities; using DotNet. tracking. API. common; using DotNet. tracking. API. controllers; using DotNet. tracking. API. models; /// <summary> /// ApiErrorHandleAttribute /// global exception handling ///// modify the record //// 2016-10-31 version: 1.0 song Biao created a file. ///// <Author> /// <name> song Biao </name> /// <date> </date> /// </author>/ // </summary> public class ApiErrorHandleAttribute: system. web. http. filters. exceptionFilterAttribute {// <summary> // unified Exception Handling // </summary> // <param name = "actionExecutedContext"> </param> public override void OnException (System. web. http. filters. httpActionExecutedContext actionExecutedContext) {base. onException (actionExecutedContext); // gets the error message var errorMessage = actionExecutedContext when an exception occurs. exception. message; // exception record string parameters = APIOperateContext. getRequestParameters (); NLogHelper. trace (actionExecutedContext. exception, BaseSystemInfo. systemCode + "ApiErrorHandleAttribute OnException complete request address and parameters:" + parameters); // Add an exception email from 2016-11-01 to remind NLogHelper. infoMail (actionExecutedContext. exception, BaseSystemInfo. systemCode + "ApiErrorHandleAttribute OnException complete request address and parameters:" + parameters); var result = new ApiResultModel () {Status = HttpStatusCode. badRequest, ErrorMessage = errorMessage}; // repackage the returned message actionExecutedContext. response = actionExecutedContext. request. createResponse (result. status, result );}}
5. context of interface operations
Using DotNet. business; using DotNet. model; using DotNet. utilities; /// <summary> /// APIOperateContext // context of the interface operation // some common context-related things are put here for processing // modify the record/ //// 2016-10-31: 1.0 song Biao created a file. ///// <Author> /// <name> song Biao </name> /// <date> </date> /// </author>/ /// </summary> public class APIOperateContext {// <summary> // obtain the current operation context (create an operation context for each server thread that processes browser requests) /// </summary> public static APIOperateContext Current {get {APIOperateContext oContext = CallContext. getData (typeof (APIOperateContext ). name) as APIOperateContext; if (oContext = null) {oContext = new APIOperat EContext (); CallContext. setData (typeof (APIOperateContext ). name, oContext) ;}return oContext ;}} # region Http context and related attributes // <summary> // Http context // </summary> public HttpContext ContextHttp {get {return HttpContext. current; }}/// <summary> // output object // </summary> public HttpResponse Response {get {return ContextHttp. response; }}/// <summary> /// request object // </summary> public HttpRequest Re Quest {get {return ContextHttp. request; }}/// <summary> // Session Object // </summary> System. web. sessionState. httpSessionState Session {get {return ContextHttp. session ;}# endregion /// <summary> /// get all request parameters, get and post simplified version /// </summary> public static string GetRequestParameters () {string query = HttpContext. current. request. url. query; NameValueCollection nvc; string baseUrl; ParseUrl (query, Out baseUrl, out nvc); List <string> list = new List <string> () {}; foreach (var key in nvc. allKeys) {list. add (key + "=" + nvc [key]);} var form = HttpContext. current. request. form; foreach (var key in form. allKeys) {list. add (key + "=" + form [key]);} string result = HttpContext. current. request. url. absoluteUri + "? "+ String. join ("&", list); return result ;} /// <summary> /// analyze the parameter information in the url string /// // For the get request /// </summary> /// <param name = "url"> input URL </param> /// <param name = "baseUrl"> Basic output URL </param> /// <param name = "nvc"> Output Analysis (parameter name, 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); // start the analysis parameter on 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 "));}} /// <summary> /// System ID /// </summary> public string SystemCode {get {return Request ["systemCode"]? "Base" ;}/// <summary> /// permission ID /// </summary> public string PermissionCode {get {return Request ["permissionCode"];} /// <summary> // AppKey sent from the application of the access interface /// </summary> public string AppKey {get {return Request ["appKey"];} /// <summary> // AppSecret sent from the application of the access interface /// </summary> public string AppSecret {get {return Request ["appSecret"];} private BaseUserInfo _ userInfo = null; // <summar Y> /// obtain the current user /// the user obtained through the AppKey and AppSecret interfaces /// </summary> /// <returns> </returns> public BaseUserInfo UserInfo {get {BaseUserInfo userInfo = null; baseUserEntity userEntity = BaseUserManager. getObjectByCodeByCache (AppKey); if (userEntity! = Null) {if (BaseServicesLicenseManager. checkServiceByCache (userEntity. id, AppSecret) {userInfo = new BaseUserInfo (); userInfo. id = userEntity. id; userInfo. realName = userEntity. realName; userInfo. userName = userEntity. userName; userInfo. IPAddress = Utilities. getIPAddress (true) ;}} return userInfo ;}} # region Business Database Connection // <summary> // Business Database Connection // </summary> public static IDbHelper BusinessDbHelper {get {return DbHelperFactory. getHelper (BaseSystemInfo. businessDbType, BaseSystemInfo. businessDbConnection );}} # endregion # region user center database connection // <summary> // user center database connection // </summary> public static IDbHelper UserCenterDbHelper {get {return DbHelperFactory. getHelper (BaseSystemInfo. userCenterDbType, BaseSystemInfo. userCenterDbConnection) ;}# endregion}
7. Unified return format entity
/// <Summary> /// ApiResultModel /// unified return format entity ///// modify the record //// 2016-10-31 version: 1.0 create a file. ///// <Author> /// <name> song Biao </name> /// <date> </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 interfaces
/// <Summary> /// MessageBookController /// message related interface ///// modify the record ///// 2016-10-31 version: 1.0 create a file. ///// <Author> /// <name> song Biao </name> /// <date> </date> /// </author>/ /// </summary> [ApiAuthFilter] public class CustomerMessageController: apiController {// <summary> // Save the message of the ticket No. /// </summary> /// <param name = "messageBook"> </param> /// <returns> </returns> [HttpPost] // Add this tag public IHttpActionResult Add ([FromBody] MsgbookCusEntity messageBook) If you do not need to verify the tag) {BaseResult bas EResult = new BaseResult (); if (string. isNullOrWhiteSpace (messageBook. systemFrom) {baseResult. status = false; baseResult. statusMessage = "SystemFrom parameter cannot be blank";} else {try {MsgbookCusManager manager = new MsgbookCusManager (APIOperateContext. businessDbHelper, APIOperateContext. current. userInfo); MsgbookCusEntity model = new MsgbookCusEntity (); model. id = Guid. newGuid (). toString ("N"); model. message = MessageBook. message; model. sendEmail = messageBook. sendEmail; model. sendTelephone = messageBook. sendTelephone; model. message = messageBook. message; model. billCode = messageBook. billCode; model. systemFrom = messageBook. systemFrom; model. deletionStateCode = 0; manager. add (model, false, false); baseResult. status = true; baseResult. statusMessage = "added successfully. ";} Catch (Exception ex) {NLogHelper. warn (ex, "mermermessagecontroller AddBillMessage exception"); baseResult. status = false; baseResult. statusMessage = "exception:" + ex. message ;}} return OK (baseResult );} /// <summary> /// obtain the message of a ticket 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 (APIOperateContext. businessDbHelper, APIOperateContext. current. userInfo); List <MsgbookCusEntity> list = new List <MsgbookCusEntity> (); list = manager. getList <MsgbookCusEntity> (new KeyValuePair <string, object> (MsgbookCusEntity. fieldBillCode, billCode), new KeyValuePair <string, object> (MsgbookCusEntity. fieldDeletionStateCode, 0); jsonResult. status = true; jsonResult. recordCount = list. count; jsonResult. data = list; jsonResult. statusMessage = "obtained successfully";} catch (Exception ex) {NLogHelper. warn (ex, "mermermessagecontroller AddBillMessage exception"); jsonResult. status = false; jsonResult. statusMessage = "exception:" + ex. message;} return OK (jsonResult );}}
9. Interface call Method
/// <Summary> /// call the Test message interface /// </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 (); postValues. add ("Message", "Enter your Message content"); postValues. add ("SendEmail", "youemail@qq.com"); postValues. add ("SendTelephone", "021-60375335"); postValues. add ("Code", "661137858"); postValues. add ("AppKey", "wssavbcn"); postValues. add ("AppSecret", "350e66b1e6564b0a817163erwwwwe8"); postValues. add ("SystemFrom", "official website"); byte [] responseArray = webClient. uploadValues (url, postValues); string response = Encoding. UTF8.GetString (responseArray); return Content (response );}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.