自学内容网 自学内容网

C#集成WebApi

1 安装依赖

在包管理器安装以下依赖包

Microsoft.AspNet.Cors
Microsoft.Owin.Cors
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Hosting
Microsoft.Owin.Host.HttpListener
Swashbuckle

2 修改Startup.cs

using Owin;
using Swashbuckle.Application;
using System;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;


namespace FanucFocasMdc
{
    public class Startup
    {
        /// <summary>
        /// 配置webApi文本格式、路由规则、跨域规则等参数
        /// </summary>
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));//解决跨域问题,需要nuget Cors

            config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{action}/{id}",
                 defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
                 );
            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            //Swagger接口文档
            config
                 .EnableSwagger(c => {
                     c.SingleApiVersion("v1", "一工机器人有限公司FANUC接口文档");
                     c.IncludeXmlComments(GetXMLDocumentPath());
                 })
                 .EnableSwaggerUi();
            //清除xml格式,使用json格式
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            appBuilder.UseWebApi(config);
        }
        private string GetXMLDocumentPath()
        {
            return AppDomain.CurrentDomain.BaseDirectory + "FanucFocasMdc.xml";
        }
    }
}

3 修改program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FanucFocasMdc
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
           // Application.Run(new Form1());
            Application.Run(new WebApiForm());

        }
    }
}

4 控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Windows.Forms;
using System.Windows.Input;
using IoTClient.Clients.PLC;
using IoTClient.Common.Enums;
using IoTClient.Common.Helper;
using IoTClient.Tool.Common;
using Swashbuckle.AspNetCore.Swagger;
using Talk.Linq.Extensions;

namespace IoTClient.Api
{
    /// <summary>
    /// 西门子plc API
    /// </summary>
    [RoutePrefix("api/Siemens")]
    public class SiemensController : ApiController
    {
        //西门子客户端
        SiemensClient client;
      

        [HttpGet]
        public Boolean connect(String ip, int port)
        {
            var config = ConnectionConfig.GetConfig();
            config.S71500_IP = ip;
            config.S71500_Port = Convert.ToString(port);
            config.S71500_Slot = "0";
            config.S71500_Rack = "0";
            byte slot = 0;
            byte rack = 0;
            client = new SiemensClient(SiemensVersion.S7_1500, ip,port, slot, rack,1500);
            var result = client.Open();
            if (!result.IsSucceed)
            {
                LogHelper.WriteInfoLog($"ip;{ip},端口:{port},连接失败,{result.Err}", true);
                return false;
            }
            return true;

        }
    }
}

5 集成logHelp

标题安装log4net包

log4net

创建LogHelper类以及log4net.config配置文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;

//为项目注册Log4Net.config配置文件
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
namespace Common
{
    public class LogHelper
    {
        #region 事件
        public static event Action<string> WriteInfoLogEvnet;
        public static event Action<string> WriteErrorLogEvnet;
        #endregion
        private LogHelper()
        {

        }
        private static readonly ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        private static readonly ILog logerror = log4net.LogManager.GetLogger("logerror");

        public static void WriteInfoLog(string info, bool isRaiseLogEvent = false)
        {
            if (WriteInfoLogEvnet != null && isRaiseLogEvent)
            {
                WriteInfoLogEvnet(info);
            }
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(info);
            }
        }
        public static void WriteErrorLog(string info, bool isRaiseLogEvent = true)
        {
            if (WriteErrorLogEvnet != null && isRaiseLogEvent)
            {
                WriteErrorLogEvnet(info);
            }
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info);
            }
        }
        public static void WriteErrorLog(string info, Exception se, bool isRaiseLogEvent = true)
        {
            if (WriteErrorLogEvnet != null && isRaiseLogEvent)
            {
                WriteErrorLogEvnet(info + se.Message);
            }
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info, se);
            }
        }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <log4net>
    <logger name="logerror">
      <level value="ERROR" />
      <appender-ref ref="ErrorAppender" />
    </logger>
    <logger name="loginfo">
      <level value="INFO" />
      <appender-ref ref="InfoAppender" />
    </logger>
    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\\LogError\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="MaxFileSize" value="10240" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyy/yyyyMM/yyyyMMdd/MMdd_HH&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="时间:%d %n信息:%m%n" />
      </layout>
    </appender>
    <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\\LogInfo\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyy/yyyyMM/yyyyMMdd/MMdd_HH&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="时间:%d %n信息:%m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>

6 集成ConfigurationManager

在项目中,我们习惯使用 ConfigurationManager 来读取一些常量。如链接数据库字符串、一些需配置的数据(微信、QQ、支付宝)等的配置。我们需要把这些数据记录在 app.config 或者 web.config 中。接下来我们具体看一下 ConfigurationManager :

标题通过 AppSettings 来获取数据,简单使用案例

using System;  
using System.Configuration;  

namespace ConsoleApplication1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            ReadAllSettings();  
            ReadSetting("Setting1");  
            ReadSetting("NotValid");  
            AddUpdateAppSettings("NewSetting", "May 7, 2014");  
            AddUpdateAppSettings("Setting1", "May 8, 2014");  
            ReadAllSettings();  
        }  

        static void ReadAllSettings()  
        {  
            try  
            {  
                var appSettings = ConfigurationManager.AppSettings;  

                if (appSettings.Count == 0)  
                {  
                    Console.WriteLine("AppSettings is empty.");  
                }  
                else  
                {  
                    foreach (var key in appSettings.AllKeys)  
                    {  
                        Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);  
                    }  
                }  
            }  
            catch (ConfigurationErrorsException)  
            {  
                Console.WriteLine("Error reading app settings");  
            }  
        }  

        static void ReadSetting(string key)  
        {  
            try  
            {  
                var appSettings = ConfigurationManager.AppSettings;  
                string result = appSettings[key] ?? "Not Found";  
                Console.WriteLine(result);  
            }  
            catch (ConfigurationErrorsException)  
            {  
                Console.WriteLine("Error reading app settings");  
            }  
        }  

        static void AddUpdateAppSettings(string key, string value)  
        {  
            try  
            {  
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
                var settings = configFile.AppSettings.Settings;  
                if (settings[key] == null)  
                {  
                    settings.Add(key, value);  
                }  
                else  
                {  
                    settings[key].Value = value;  
                }  
                configFile.Save(ConfigurationSaveMode.Modified);  
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);  
            }  
            catch (ConfigurationErrorsException)  
            {  
                Console.WriteLine("Error writing app settings");  
            }  
        }  
    }  
}

在文件 App.config 中配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <appSettings>
    <add key="Setting1" value="May 5,2018"/>
    <add key="Setting2" value="May 5,2017"/>
  </appSettings>
</configuration>

标题通过使用 ConnectionStrings 来获取数据,使用案例

using System;  
using System.Configuration;  
using System.Data.SqlClient;  

namespace ConsoleApplication1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            ReadUsers();  
        }  

        static void ReadUsers()  
        {  
            var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;  
            string queryString = "SELECT Id, Name FROM abpusers;";  
            using (var connection = new SqlConnection(connectionString))  
            {  
                var command = new SqlCommand(queryString, connection);  
                connection.Open();  
                using (var reader = command.ExecuteReader())  
                {  
                    while (reader.Read())  
                    {  
                        Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));  
                    }  
                }  
            }  
        }  
    }  
}

在 App.config 中配置数据库链接字符串:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <appSettings>
    <add key="Setting1" value="May 5,2018"/>
    <add key="Setting2" value="May 5,2017"/>
  </appSettings>

  <connectionStrings>
    <add name="Default" connectionString="Server=127.0.0.1; Database=CityManage; Trusted_Connection=False; Uid=root; pwd=zxx123456;" providerName="System.Data.SqlClient" />
    <add name="Abp.Redis.Cache" connectionString="localhost" />
  </connectionStrings>

</configuration>

原文地址:https://blog.csdn.net/weixin_38501485/article/details/144306508

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!