当前位置:网站首页>[recommended by bloggers] asp Net WebService background data API JSON (with source code)

[recommended by bloggers] asp Net WebService background data API JSON (with source code)

2022-07-06 10:53:00 xcLeigh

【 Bloggers recommend 】asp.net WebService Background data API( Source code attached )

Web service It's a program based web Applications for , For developing distributed, interoperable applications , It is also a kind of web service
WebService There are several characteristics of :
1. Use XML( Standard universal markup language ) As the format of data interaction .
2. Cross-platform sex , Because use XML So as long as the local application can connect to the network for parsing XML Data exchange can be realized , Like Android 、IOS、WindowsPhone And so on Web service Data interaction .
3. be based on HTTP agreement , Directly across the firewall , Universal strong ;
The code posted in the interface is only the main implementation process , Specific implementation methods , For external methods, see the source code download of project resources

Code implementation

  • 1. Provide front-end data Additions and deletions API;
  • 2. Built in use mysql、oracle database , Multi configuration , The required database can be automatically switched in the configuration file ;
  • 3.api Interface filter mechanism , You can filter the requests you want to filter ;
  • 4. Can provide json and xml Data format ;
  • 5. Code download can be used directly ;
  • 6. Implement different databases , Carry out different sql sentence ;
  • 7. contains websocket Server side , Receive processing client websocket data ;
  • 8. Incidental websocket Client source code ;
  • 9. With text log file output ;

webservice Simple creation process

First, learn how to simply create one according to this tutorial web service , In order to better understand
C# in WebService Creation and invocation of

1. Configure global application classes Global.asax

Application_Start and Application_End
The first time you visit the site , establish HttpApplication object , It's going to trigger Application_Start, And create HttpApplication Instance pool , The application gets the instance from the pool upon request , To deal with . Of all the HttpApplication Instance idle timeout , Trigger application pool recycle , Or it will be triggered when the site is restarted Application_End event , The idle timeout of the application pool can be iis Set up , Under the site bin The files in the directory have changed ,webconfig Configuration changes and other events that cause the site to restart will be triggered Application_End.

Session_Start and Session_End
Single user access Web When applied , Start a session , The server creates a separate for the user Session object , And trigger Session_Start event , here Session In a usable state . The user can initiate several requests after the session is established , When the server does not receive a user request for a period of time , When the session timeout is reached , Trigger Session_End event , Server release saved for current user Session Of memory . Can also be invoked in the application. Session.Abandon() You can manually cancel Session, Empty the saved by the server Session, Until it's called again Session when , It will trigger again Session_Start, however SessionID No change . All will trigger Application_End All events will be triggered before this Session_Start. Can be in Web.Config Add settings Session Expiration time (timeout In minutes ).

Application_BeginRequest and Application_EndRequest
After the user session starts , Each request is triggered Application_BeginRequest event , And triggered when the request is completed Application_EndRequest event .

Application_BeginRequest  Configure filtering 

#region  Filter clients xss Malicious script submission 
if (Request.Cookies != null)
{
    if (XSSFilter.CookieData())
    {
        Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Response.Write(JsonUtil.getText1Json(" You submitted Cookie The data has malicious characters !"));
        Response.End();
    }
}
if (Request.UrlReferrer != null)
{
    if (XSSFilter.referer())
    {
        Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Response.Write(JsonUtil.getText1Json(" You submitted Referrer The data has malicious characters !"));
        Response.End();
    }
}
if (Request.RequestType.ToUpper() == "POST")
{
    if (XSSFilter.PostData())
    {
        Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Response.Write(JsonUtil.getText1Json(" You submitted Post The data has malicious characters !"));
        Response.End();
    }
}
if (Request.RequestType.ToUpper() == "GET")
{
    if (XSSFilter.GetData())
    {
        Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Response.Write(JsonUtil.getText1Json(" You submitted Get The data has malicious characters !"));
        Response.End();
    }
}
#endregion

#region  Filter parameters 
 // Traverse Post Parameters , Except for hidden fields 
 foreach (string i in this.Request.Form)
 {
     if (i == "__VIEWSTATE") continue;
     this.goErr(this.Request.Form[i].ToString());
 }
 // Traverse Get Parameters . 
 foreach (string i in this.Request.QueryString)
 {
     this.goErr(this.Request.QueryString[i].ToString());
 }
 #endregion

3. To configure POST,GET Request returns JOSN

Web.config

<system.web>
	<webServices>
      <protocols>
        <add name="HttpPost" />
        <add name="HttpGet" />
        <add name="HttpSoap" />
        <add name="Documentation" />
      </protocols>
    </webServices>
</system.web>
      
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET" />
        <add name="Access-Control-Allow-Headers" value="x-requested-with" />
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

2. newly build asmx WEB Service document

 Insert picture description here
The interface configuration after construction
 Insert picture description here
dwsh.asmx Code

using DataServiceBLL;
using DataServiceUtil;
using System;
using System.Web.Script.Services;
using System.Web.Services;

namespace DataServiceAPI.dsa.api.v1.data
{
    /// <summary>
    /// dwsh  Summary description of 
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    //  To allow  ASP.NET AJAX  Call this from script  Web  service , Please uncomment the following lines . 
    // [System.Web.Script.Services.ScriptService]
    public class dwsh : System.Web.Services.WebService
    {
        #region  Instantiation 
        public OperDataBLL operDataBLL = new OperDataBLL();
        #endregion

		//api See the effect code below for the interface 
    }
}

3. Effect display

3.1 newly added api

 Insert picture description here
Code


#region  newly added 
[WebMethod(Description = " New data ")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void add(string token, string name, string codedata, string detail)
{
   if (token != ConfigurationHelperUtil.DSA_TOKEN)
   {
       Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
       Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
       Context.Response.Write(JsonUtil.getError205Json());// can json, Textable , can xml
       Context.Response.End();
   }
   else
   {
       string result = " Successful operation !";
       int code = 200;
       try
       {
           string sql = "";
           string db = ConfigurationHelperUtil.DSA_DB;
           int num = 0;
           if (db.ToUpper() == "MYSQL")
           {
               sql = "insert into SMS_TEST(NAME, CODE, DETAIL, INSERTTIME)";
               sql += " values('" + name + "', '" + codedata + "', '" + detail + "', now())";
               num = operDataBLL.OperData(sql);
           }
           else if (db.ToUpper() == "ORACLE")
           {
               sql = "insert into SMS_TEST(id,NAME,CODE,DETAIL,INSERTTIME)";
               sql += " values(seq_dswh_id.nextval, '" + name + "', '" + codedata + "', '" + detail + "', sysdate)";
               num = operDataBLL.OperOracleData(sql);
           }
           OperLogUtil.WriteFileLog(" New operation sql:" + sql, ConfigurationHelperUtil.DSA_LOG_TYPE_INFO);
           if (num > 0)
           {
               result = " Successful operation ";
           }
           else
           {
               result = " Data not updated ";
               code = 201;
           }
       }
       catch (Exception)
       {
           result = " Abnormal operation !";
           code = 202;
       }
       string resultJson = JsonUtil.getTextJson(code, result, 1, "[]");
       Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
       Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
       Context.Response.Write(resultJson);// can json, Textable , can xml
       Context.Response.End();
   }
}
#endregion

3.2 modify api

 Insert picture description here
Code

#region  modify 
[WebMethod(Description = " Data modification ")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void update(string token,string id, string name, string codedata, string detail)
{
   if (token != ConfigurationHelperUtil.DSA_TOKEN)
   {
       Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
       Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
       Context.Response.Write(JsonUtil.getError205Json());// can json, Textable , can xml
       Context.Response.End();
   }
   else
   {
       string result = " Successful operation !";
       int code = 200;
       try
       {
           string sql = "";
           string db = ConfigurationHelperUtil.DSA_DB;
           int num = 0;
           if (db.ToUpper() == "MYSQL")
           {
               sql = "update SMS_TEST set NAME='" + name + "', CODE= '" + codedata + "', DETAIL='" + detail + "' where id="+id;
               num = operDataBLL.OperData(sql);
           }
           else if (db.ToUpper() == "ORACLE")
           {
               sql = "update SMS_TEST set NAME= '" + name + "',CODE= '" + codedata + "',DETAIL= '" + detail + "' where id="+id;
               num = operDataBLL.OperOracleData(sql);
           }
           OperLogUtil.WriteFileLog(" Modify the operating sql:" + sql, ConfigurationHelperUtil.DSA_LOG_TYPE_INFO);
           if (num > 0)
           {
               result = " Successful operation ";
           }
           else
           {
               result = " Data not updated ";
               code = 201;
           }
       }
       catch (Exception)
       {
           result = " Abnormal operation !";
           code = 202;
       }
       string resultJson = JsonUtil.getTextJson(code, result, 1, "[]");
       Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
       Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
       Context.Response.Write(resultJson);// can json, Textable , can xml
       Context.Response.End();
   }
}
#endregion

3.3 list api

 Insert picture description here
Code

#region  Query list  
[WebMethod(Description = " list ")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
//[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public void getlist(string token, string name)
{
    if (token != ConfigurationHelperUtil.DSA_TOKEN)
    {
        Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Context.Response.Write(JsonUtil.getError205Json());// can json, Textable , can xml
        Context.Response.End();
    }
    else
    {
        string result = "";
        try
        {
            if (name == "" || name == null || name == "null")
            {
                name = "";
            }
            else
            {
                name = " and name like '%" + name + "%'";
            }
            string sql = "select * from SMS_TEST t where 1=1" + name;
            string db = ConfigurationHelperUtil.DSA_DB;
            OperLogUtil.WriteFileLog(" Query operation sql:" + sql, ConfigurationHelperUtil.DSA_LOG_TYPE_INFO);
            if (db.ToUpper() == "MYSQL")
            {
                result = operDataBLL.getData(sql);
            }
            else if (db.ToUpper() == "ORACLE")
            {
                result = operDataBLL.getOracleData(sql);
            }
        }
        catch (Exception)
        {
            result = JsonUtil.getError201Json();
        }
        Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Context.Response.Write(result);// can json, Textable , can xml
        Context.Response.End();
    }
}

#endregion

3.4 Delete api

 Insert picture description here
Code

#region  Delete 
[WebMethod(Description = " Data deletion ")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void del(string token, string id)
{
    if (token != ConfigurationHelperUtil.DSA_TOKEN)
    {
        Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Context.Response.Write(JsonUtil.getError205Json());// can json, Textable , can xml
        Context.Response.End();
    }
    else
    {
        string result = " Successful operation !";
        int code = 200;
        try
        {
            string sql = "";
            string db = ConfigurationHelperUtil.DSA_DB;
            int num = 0;
            if (db.ToUpper() == "MYSQL")
            {
                sql = "delete SMS_TESTdelete from SMS_TEST where id="+id;
                num = operDataBLL.OperData(sql);
            }
            else if (db.ToUpper() == "ORACLE")
            {
                sql = "delete SMS_TEST where id="+id;
                num = operDataBLL.OperOracleData(sql);
            }
            OperLogUtil.WriteFileLog(" Delete operation sql:" + sql, ConfigurationHelperUtil.DSA_LOG_TYPE_INFO);
            if (num > 0)
            {
                result = " Successful operation ";
            }
            else
            {
                result = " Data not updated ";
                code = 201;
            }
        }
        catch (Exception)
        {
            result = " Abnormal operation !";
            code = 202;
        }
        string resultJson = JsonUtil.getTextJson(code, result, 1, "[]");
        Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Context.Response.Write(resultJson);// can json, Textable , can xml
        Context.Response.End();
    }
}
#endregion

3.5 Paging list api

 Insert picture description here
Code

#region  Query list paging 
[WebMethod(Description = " Paging list ")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
//[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public void getfyList(string token, string limit, string start, string name)
{
    if (token != ConfigurationHelperUtil.DSA_TOKEN)
    {
        Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Context.Response.Write(JsonUtil.getError205Json());// can json, Textable , can xml
        Context.Response.End();
    }
    else
    {
        string result = "";
        if (!StrUtil.isNum(limit) || !StrUtil.isNum(start))// Verify whether the parameters are qualified 
        {
            result = JsonUtil.getError203Json();
        }
        else
        {
            try
            {
                if (name == "" || name == null || name == "null")
                {
                    name = "";
                }
                else
                {
                    name = " and name like '%" + name + "%'";
                }
                string db = ConfigurationHelperUtil.DSA_DB;
                if (db.ToUpper() == "MYSQL")
                {
                    //limit a,b  a Is the number of starting lines   b For a few lines 
                    int ks = (int.Parse(start) - 1) * int.Parse(limit);
                    string sql = "SELECT * FROM SMS_TEST WHERE 1=1" + name + " ORDER BY INSERTTIME desc LIMIT " + ks + ", " + limit;
                    result = operDataBLL.getFyData(sql, "SMS_TEST");
                    OperLogUtil.WriteFileLog(" Paging list operation sql:" + sql, ConfigurationHelperUtil.DSA_LOG_TYPE_INFO);
                }
                else if (db.ToUpper() == "ORACLE")
                {
                    string sql = "SELECT * FROM SMS_TEST WHERE 1=1" + name;
                    //false desc   true asc
                    result = operDataBLL.getFyOracleData(sql, "INSERTTIME", false, int.Parse(limit), int.Parse(start));
                    OperLogUtil.WriteFileLog(" Paging list operation sql:" + sql, ConfigurationHelperUtil.DSA_LOG_TYPE_INFO);
                }
            }
            catch (Exception)
            {
                result = JsonUtil.getError201Json();
            }
        }
        Context.Response.Charset = ConfigurationHelperUtil.DSA_Encode;
        Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(ConfigurationHelperUtil.DSA_Encode);
        Context.Response.Write(result);// can json, Textable , can xml
        Context.Response.End();
    }
}

#endregion

4. built-in websocket Server side

  • To start websocket, Just uncomment these lines of code
protected void Application_Start(object sender, EventArgs e)
{
    // start-up webScoket
    //Thread thread2 = new Thread(new ThreadStart(WebScoket.startWebScoket));// Create thread 
    //thread2.Start(); // Start thread 

    //WebScoket.startWebScoket();// be used for CMS

}
  • websocket Code
using DataServiceBLL;
using DataServiceUtil;
using Newtonsoft.Json.Linq;
using StriveEngine;
using StriveEngine.Core;
using StriveEngine.Tcp.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace DataServiceAPI.App_Code
{
    public class WebScoket
    {
        private static ITcpServerEngine tcpServerEngine;
        private static bool hasTcpServerEngineInitialized;
        public static OperDataBLL operDataBLL = new OperDataBLL();
        public static void startWebScoket()
        {
            OperLogUtil.WriteFileLog(" start-up WebScoket", ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
            try
            {
                if (tcpServerEngine == null)
                {
                    tcpServerEngine = NetworkEngineFactory.CreateTextTcpServerEngine(int.Parse(ConfigurationHelperUtil.DSA_WebScoket), new DefaultTextContractHelper("\0"));//DefaultTextContractHelper yes StriveEngine Built in ITextContractHelper Realization . Use UTF-8 Yes EndToken Encoding . 
                }

                if (hasTcpServerEngineInitialized)
                {
                    tcpServerEngine.ChangeListenerState(true);
                }
                else
                {
                    InitializeTcpServerEngine();
                }
            }
            catch (Exception ee)
            {
                OperLogUtil.WriteFileLog(ee.Message, ConfigurationHelperUtil.DSA_LOG_TYPE_ERROR);
            }
        }

        public static void InitializeTcpServerEngine()
        {
            tcpServerEngine.ClientCountChanged += new CbDelegate<int>(tcpServerEngine_ClientCountChanged);
            tcpServerEngine.ClientConnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientConnected);
            tcpServerEngine.ClientDisconnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientDisconnected);
            tcpServerEngine.MessageReceived += new CbDelegate<IPEndPoint, byte[]>(tcpServerEngine_MessageReceived);
            tcpServerEngine.Initialize();
            hasTcpServerEngineInitialized = true;
        }
        public static void tcpServerEngine_ClientCountChanged(int count)
        {
            OperLogUtil.WriteFileLog(" Online quantity : " + count, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
        }
        public static void tcpServerEngine_ClientConnected(System.Net.IPEndPoint ipe)
        {
            string msg = string.Format("{0}  go online ", ipe);
            OperLogUtil.WriteFileLog(msg, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
        }
        public static void tcpServerEngine_ClientDisconnected(System.Net.IPEndPoint ipe)
        {
            string msg = string.Format("{0}  Offline ", ipe);
            OperLogUtil.WriteFileLog(msg, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
        }
        public static void tcpServerEngine_MessageReceived(IPEndPoint client, byte[] bMsg)
        {
            string msg = System.Text.Encoding.UTF8.GetString(bMsg); // message UTF-8 code 
            msg = msg.Substring(0, msg.Length - 1); // End tag "\0" To eliminate 
            OperLogUtil.WriteFileLog(" received :" + client.Address + ":" + msg, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);

            #region  Processing received data 
            // Process the received data here 
            #endregion
        }

        #region  Push a single message according to the client 
        public static void sendInfo(IPEndPoint client, string msg)
        {
            try
            {
                msg = msg + "\0";// "\0"  Indicates the end of a message 
                byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(msg);// message UTF-8 code 
                tcpServerEngine.SendMessageToClient(client, bMsg);
            }
            catch (Exception ee)
            {
                OperLogUtil.WriteFileLog(ee.Message, ConfigurationHelperUtil.DSA_LOG_TYPE_ERROR);
            }
        }
        #endregion

        #region  Push message , Push all online clients 

        public static void sendInfoAll(string msg)
        {
            try
            {
                List<IPEndPoint> list = tcpServerEngine.GetClientList();// Get online devices 
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        try
                        {
                            IPEndPoint client = list[i];
                            if (client == null)
                            {// There is no client 
                                OperLogUtil.WriteFileLog(" There is no client :" + client.Address + ":" + client.Port, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
                            }
                            else if (!tcpServerEngine.IsClientOnline(client))
                            {// The client is not online 
                                OperLogUtil.WriteFileLog(" The client is not online :" + client.Address + ":" + client.Port, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
                            }
                            else
                            {
                                msg = msg + "\0";// "\0"  Indicates the end of a message 
                                byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(msg);// message UTF-8 code 
                                tcpServerEngine.SendMessageToClient(client, bMsg);
                                OperLogUtil.WriteFileLog(" client :" + client.Address + ":" + client.Port + " send out :" + msg, ConfigurationHelperUtil.DSA_LOG_TYPE_WEBSCOKET);
                            }
                        }
                        catch (Exception ee)
                        {
                            OperLogUtil.WriteFileLog("sendInfoAll1" + ee.Message, ConfigurationHelperUtil.DSA_LOG_TYPE_ERROR);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                OperLogUtil.WriteFileLog("sendInfoAll2" + ee.Message, ConfigurationHelperUtil.DSA_LOG_TYPE_ERROR);
            }
        }
        #endregion
        

        #region  Judge whether it is a string or a number 
        /**
         *  Determine whether the string is a number 
         */
        public static Boolean isNumber(String value)
        {
            return isInteger(value);
        }

        /**
         *  Determine whether the string is an integer 
         */
        public static Boolean isInteger(String value)
        {
            try
            {
                int num = int.Parse(value);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        

        #endregion
    }
}

5. Source download

【 Bloggers recommend 】asp.net WebService Background data API JSON( Source code attached )

原网站

版权声明
本文为[xcLeigh]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060912197813.html