Web api record request, webapi

Source: Internet
Author: User

Web api record request, webapi

Some time ago, a protocol site was developed for the client (Android/IOS), and the call frequency of each protocol was counted for the business. Logs are recorded in the log system.

After a brief analysis, there are roughly two technical solutions:

Solution A: Protocol for each business module must be separately tracked.

Solution B: encapsulate an HttpModule. Record all requests.

The advantages and disadvantages of Solution A and solution B are not analyzed. There are two groups in our project to make similar Protocol sites, and we adopt solution B. Another group adopted solution.

Here I will focus on the reasons for using solution B:

1. bother a person. After one person completes development, others will not spend any time to add more records. Unified records.

2. To facilitate troubleshooting, you can also record request parameters and output parameters, and do not need to record the returned values in the business. Business development only cares about the business. Record General logs in the business.

The code is relatively simple. The Protocol follows the Json string sent by the Post request. All Request strings are in Request. InputStream. One Processing request for two files (Handle. cs) and one obtaining data (CatchTextStream. cs)

Handle. cs

Using System; using System. IO; using System. web; using Logs; namespace HttpModule. api {public class Handle: IHttpModule {private string json = string. empty; private string requestItemKey = "request. json "; private string responseItemKey =" response. json "; void IHttpModule. dispose () {} void IHttpModule. init (HttpApplication context) {context. beginRequest + = new EventHandler (beginRequest); context. endR Equest + = new EventHandler (endRequest);} private void beginRequest (object sender, EventArgs e) {HttpApplication application = (HttpApplication) sender; var context = application. context; if (context = null) {return;} // exclude unnecessary links if (context. request. inputStream. length> 0) {context. response. filter = new CatchTextStream (context. response. filter, responseItemKey); context. request. inputStream. posit Ion = 0; // set the stream position StreamReader reader = new StreamReader (context. request. inputStream); // request stream string json = reader. readToEnd (); context. request. inputStream. seek (0, SeekOrigin. end); // reset the stream reading position. If it is not reset, The json string context cannot be obtained in the method. request. requestContext. httpContext. items [requestItemKey] = json;} else // only records the {_ log. info ("request url:" + context. request. url) ;}} private void endRequest (object sender, EventArg S e) {HttpApplication application = (HttpApplication) sender; var context = application. context; if (context. request. requestContext. httpContext. items. contains (requestItemKey) {string requestJson = context. request. requestContext. httpContext. items [requestItemKey]. toString (); string responseJson = context. request. requestContext. httpContext. items [responseItemKey]. toString (); // the return value of the current request status contains code: 0, indicating the protocol. Request success status = Log System ID, 1 = normal return of the request, 0 = request exception int status = responseJson. contains ("\" code \ ": \" 0 \"")? 1: 0; writeLog (context. request. url. localPath, requestJson, "return =" + responseJson, status) ;}} private void writeLog (string url, string parms, string msg, int status) {var entity = new Logs. logRecord ("site name", LogLevelType. monitor, url) {ParasNameValue = parms, ErrMessage = msg, Status = status}; Logs. logNetHelper. writeLog (entity );}}}

Note: The Logs package is a general record method encapsulated by a company project.

CatchTextStream. cs

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;using System.Web;namespace HttpModule.Api{    class CatchTextStream : Stream    {        private Stream output;        private List<byte> _listByte = new List<byte>();        private string _itemKey;        public CatchTextStream(Stream s, string itemKey)        {            _itemKey = itemKey;            output = s;        }        public override bool CanRead        {            get { return output.CanRead; }        }        public override bool CanSeek        {            get { return output.CanSeek; }        }        public override bool CanWrite        {            get { return output.CanWrite; }        }        public override void Flush()        {            output.Flush();            if (_listByte.Any())            {                var utf8 = Encoding.UTF8;                string json = utf8.GetString(_listByte.ToArray(), 0, _listByte.Count);                HttpContext.Current.Request.RequestContext.HttpContext.Items[_itemKey] = json;            }        }        public override long Length        {            get { return output.Length; }        }        public override long Position        {            get { return output.Position; }            set { output.Position = value; }        }        public override int Read(byte[] buffer, int offset, int count)        {            return output.Read(buffer, offset, count);        }        public override long Seek(long offset, SeekOrigin origin)        {            return output.Seek(offset, origin);        }        public override void SetLength(long value)        {            output.SetLength(value);        }        public override void Write(byte[] buffer, int offset, int count)        {            output.Write(buffer, offset, count);            if (HttpContext.Current != null)            {                if (HttpContext.Current.Request.RequestContext.HttpContext.Items.Contains(_itemKey))                {                    var temp = buffer.Skip(offset).Take(count);                    _listByte.AddRange(temp);                }            }        }    }}

Configure Modules in Web. config.

<Modules runAllManagedModulesForAllRequests = "true"> <! -- Record request logs --> <add name = "apilog" type = "HttpModule. Api. Handle, HttpModule. Api"/> </modules>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.