NetFramework
版本
vs2017软件 .Net Framework 4.6.1 在 NuGet 中下载 MySql.Data 8.0.26.0 SqlSugar 5.1.4.135 log4net 2.0.15.0 Swashbuckle 5.6.0
创建
新建 项目 ASP.NET Web 应用程序(.NET Framework) Visual C#
跨域
< system.webServer>
< httpProtocol>
< customHeaders>
< remove name = " Access-Control-Allow-Origin" />
< remove name = " Access-Control-Allow-Methods" />
< remove name = " Access-Control-Allow-Headers" />
< add name = " Access-Control-Allow-Origin" value = " *" />
< add name = " Access-Control-Allow-Methods" value = " *" />
< add name = " Access-Control-Allow-Headers" value = " *" />
</ customHeaders>
</ httpProtocol>
</ system.webServer>
protected void Application_BeginRequest ( )
{
if ( HttpContext. Current. Request. HttpMethod == "OPTIONS" )
{
HttpContext. Current. Response. End ( ) ;
}
}
配置
App_Start – WebApiConfig.cs
public static class WebApiConfig
{
public static void Register ( HttpConfiguration config)
{
config. MapHttpAttributeRoutes ( ) ;
config. Routes. MapHttpRoute (
name : "DefaultApi" ,
routeTemplate : "api/{controller}/{action}/{id}" ,
defaults: new { id = RouteParameter. Optional }
) ;
var formatters = config. Formatters. Where ( formatter =>
formatter. SupportedMediaTypes. Where ( media =>
media. MediaType. ToString ( ) == "application/xml" || media. MediaType. ToString ( ) == "text/html" ) . Count ( ) > 0 )
. ToList ( ) ;
foreach ( var match in formatters)
{
config. Formatters. Remove ( match) ;
}
var json = config. Formatters. JsonFormatter;
json. SerializerSettings. DateFormatString = "yyyy-MM-dd HH:mm:ss" ;
}
}
< configuration>
< connectionStrings>
< add name = " mysqlconn" connectionString = " database=数据库名称;server=数据库地址;uid=root;pwd=1234567;" />
< add name = " logs" connectionString = " 1" />
</ connectionStrings>
</ configuration>
public class Tools
{
public static readonly string mysqlconn = ConfigurationManager. ConnectionStrings[ "mysqlconn" ] . ConnectionString;
public static readonly string logs = ConfigurationManager. ConnectionStrings[ "logs" ] . ConnectionString;
}
日志
log4net.config 与Web.config 同级
<?xml version="1.0" encoding="utf-8"?>
< configuration>
< configSections>
< section name = " log4net" type = " log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</ configSections>
< log4net>
< appender name = " HitLogFileAppender" type = " log4net.Appender.RollingFileAppender" >
< param name = " File" value = " d:\\Log\\hit" />
< param name = " AppendToFile" value = " true" />
< param name = " MaxSizeRollBackups" value = " 10" />
< param name = " StaticLogFileName" value = " false" />
< param name = " DatePattern" value = " yyyy-MM-dd" .log" " />
< param name = " RollingStyle" value = " Date" />
< layout type = " log4net.Layout.PatternLayout" >
< param name = " ConversionPattern" value = " %d [%t] %-5p %c - %m%n %logger%newline" />
</ layout>
< filter type = " log4net.Filter.LevelRangeFilter" >
< param name = " LevelMin" value = " ERROR" />
< param name = " LevelMax" value = " OFF" />
</ filter>
</ appender>
< appender name = " warnLogFileAppender" type = " log4net.Appender.RollingFileAppender" >
< param name = " File" value = " d:\\Log\\warn" />
< param name = " AppendToFile" value = " true" />
< param name = " MaxSizeRollBackups" value = " 10" />
< param name = " StaticLogFileName" value = " false" />
< param name = " DatePattern" value = " yyyy-MM-dd" .log" " />
< param name = " RollingStyle" value = " Date" />
< layout type = " log4net.Layout.PatternLayout" >
< param name = " ConversionPattern" value = " %d [%t] %-5p %c - %m%n %logger%newline" />
</ layout>
< filter type = " log4net.Filter.LevelRangeFilter" >
< param name = " LevelMin" value = " WARN" />
< param name = " LevelMax" value = " WARN" />
</ filter>
</ appender>
< appender name = " infoLogFileAppender" type = " log4net.Appender.RollingFileAppender" >
< param name = " File" value = " d:\\Log\\info" />
< param name = " AppendToFile" value = " true" />
< param name = " MaxSizeRollBackups" value = " 10" />
< param name = " StaticLogFileName" value = " false" />
< param name = " DatePattern" value = " yyyy-MM-dd" .log" " />
< param name = " RollingStyle" value = " Date" />
< layout type = " log4net.Layout.PatternLayout" >
< param name = " ConversionPattern" value = " %d [%t] %-5p %c - %m%n %logger%newline" />
</ layout>
< filter type = " log4net.Filter.LevelRangeFilter" >
< param name = " LevelMin" value = " INFO" />
< param name = " LevelMax" value = " INFO" />
</ filter>
</ appender>
< appender name = " debugLogFileAppender" type = " log4net.Appender.RollingFileAppender" >
< param name = " File" value = " d:\\Log\\debug" />
< param name = " AppendToFile" value = " true" />
< param name = " MaxSizeRollBackups" value = " 10" />
< param name = " StaticLogFileName" value = " false" />
< param name = " DatePattern" value = " yyyy-MM-dd" .log" " />
< param name = " RollingStyle" value = " Date" />
< layout type = " log4net.Layout.PatternLayout" >
< param name = " ConversionPattern" value = " %d [%t] %-5p %c - %m%n %logger%newline" />
</ layout>
< filter type = " log4net.Filter.LevelRangeFilter" >
< param name = " LevelMin" value = " DEBUG" />
< param name = " LevelMax" value = " DEBUG" />
</ filter>
</ appender>
< appender name = " ColoredConsoleAppender" type = " log4net.Appender.ColoredConsoleAppender" >
< mapping>
< level value = " ERROR" />
< foreColor value = " Red, HighIntensity" />
</ mapping>
< mapping>
< level value = " Info" />
< foreColor value = " Green" />
</ mapping>
< layout type = " log4net.Layout.PatternLayout" >
< conversionPattern value = " %n%date{HH:mm:ss,fff} [%-5level] %m" />
</ layout>
< filter type = " log4net.Filter.LevelRangeFilter" >
< param name = " LevelMin" value = " Info" />
< param name = " LevelMax" value = " Fatal" />
</ filter>
</ appender>
< root>
< level value = " all" />
< appender-ref ref = " ColoredConsoleAppender" />
< appender-ref ref = " HitLogFileAppender" />
< appender-ref ref = " warnLogFileAppender" />
< appender-ref ref = " infoLogFileAppender" />
< appender-ref ref = " debugLogFileAppender" />
</ root>
</ log4net>
</ configuration>
public class Logs
{
private static object objLock = new object ( ) ;
private static Logs server;
private static ILog dal;
public static Logs Instance
{
get
{
lock ( objLock)
{
if ( server == null )
{
XmlConfigurator. ConfigureAndWatch ( new FileInfo ( AppDomain. CurrentDomain. BaseDirectory + "log4net.config" ) ) ;
dal = LogManager. GetLogger ( System. Reflection. MethodBase. GetCurrentMethod ( ) . DeclaringType) ;
server = new Logs ( ) ;
}
return server;
}
}
}
public void WriteDebug ( string s)
{
if ( Tools. logs == "1" )
{
dal. Debug ( s) ;
}
}
public void WriteWarn ( string s)
{
if ( Tools. logs == "1" )
{
dal. Warn ( s) ;
}
}
public void WriteInfo ( string s)
{
if ( Tools. logs == "1" )
{
dal. Info ( s) ;
}
}
public void WriteError ( string s)
{
if ( Tools. logs == "1" )
{
dal. Error ( s) ;
}
}
}
SqlSugar
public class BaseDAL
{
private static object objLock = new object ( ) ;
private static BaseDAL dal;
public static BaseDAL Instance
{
get
{
lock ( objLock)
{
if ( dal == null )
{
dal = new BaseDAL ( ) ;
}
return dal;
}
}
}
public SqlSugarClient GesmartDb ( )
{
string dbstr = Tools. mysqlconn;
SqlSugarClient Db = new SqlSugarClient ( new ConnectionConfig ( )
{
ConnectionString = dbstr,
DbType = DbType. SqlServer,
InitKeyType = InitKeyType. Attribute,
IsAutoCloseConnection = true ,
} ) ;
Db. Aop. OnLogExecuting = ( sql, pars) =>
{
Logs. Instance. WriteWarn ( sql + "\r\n" +
Db. Utilities. SerializeObject ( pars. ToDictionary ( it => it. ParameterName, it => it. Value) ) + "sql日志" ) ;
} ;
return Db;
}
}
}
统一返回
public class Response< T>
{
public int code { get ; set ; }
public string message { get ; set ; }
public T data { get ; set ; }
}
使用
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0 ;
DROP TABLE IF EXISTS ` ceshi` ;
CREATE TABLE ` ceshi` (
` id` int ( 11 ) NOT NULL AUTO_INCREMENT ,
` name` varchar ( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
` status` int ( 10 ) NULL DEFAULT NULL ,
PRIMARY KEY ( ` id` ) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO ` ceshi` VALUES ( 1 , '三生三世' , 1 ) ;
SET FOREIGN_KEY_CHECKS = 1 ;
public class Ceshi
{
public int id { get ; set ; }
public string name { get ; set ; }
public int status { get ; set ; }
}
public class DAlCeshi
{
public IEnumerable< Ceshi> GetAll ( )
{
using ( SqlSugarClient db = BaseDAL. Instance. GesmartDb ( ) )
{
var result = db. Ado. SqlQuery < Ceshi> ( @"select * from ceshi;" ) . ToList ( ) ;
return result;
}
}
}
Controllers – CeshiModel – 新建控制器(CeshiController)
public class CeshiController : ApiController
{
private DAlCeshi dAl = new DAlCeshi ( ) ;
[ HttpGet]
public Response< List< Ceshi> > GetAll ( )
{
var d = new Response< List< Ceshi> > ( )
{
code = 200 ,
message = "成功"
} ;
try {
d. data = dAl. GetAll ( ) . ToList ( ) ;
} catch ( Exception ex)
{
d. message = ex. Message;
}
return d;
}
}
认证
Utils – ApiAuthorizeAttribute.cs
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized ( HttpActionContext actionContext)
{
bool fis = actionContext. Request. Method == HttpMethod. Options;
Logs. Instance. WriteError ( "方法:::::::::" + actionContext. Request. Method + fis) ;
if ( fis)
{
return true ;
}
return true ;
}
protected override void HandleUnauthorizedRequest ( HttpActionContext actionContext)
{
var erModel = new Response< List< string > > ( )
{
code = 999 ,
message = "认证失败" ,
data = new List< string > ( )
} ;
actionContext. Response = actionContext. Request. CreateResponse ( HttpStatusCode. OK, erModel, "application/json" ) ;
}
}
Swaager
右键项目 – 属性 – 生成 – 勾选 XML文档文件 Web.config 同级新建 swagger-China.js swagger-China.js 右键 – 属性 – 高级 – 生成操作 – 嵌入的资源
'use strict' ;
window. SwaggerTranslator = {
_words : [ ] ,
translate : function ( ) {
var $this = this ;
$ ( '[data-sw-translate]' ) . each ( function ( ) {
$ ( this ) . html ( $this . _tryTranslate ( $ ( this ) . html ( ) ) ) ;
$ ( this ) . val ( $this . _tryTranslate ( $ ( this ) . val ( ) ) ) ;
$ ( this ) . attr ( 'title' , $this . _tryTranslate ( $ ( this ) . attr ( 'title' ) ) ) ;
} ) ;
} ,
setControllerSummary : function ( ) {
try {
console. log ( $ ( "#input_baseUrl" ) . val ( ) ) ;
$. ajax ( {
type : "get" ,
async : true ,
url : $ ( "#input_baseUrl" ) . val ( ) ,
dataType : "json" ,
success : function ( data ) {
var summaryDict = data. ControllerDesc;
console. log ( summaryDict) ;
var id, controllerName, strSummary;
$ ( "#resources_container .resource" ) . each ( function ( i, item ) {
id = $ ( item) . attr ( "id" ) ;
if ( id) {
controllerName = id. substring ( 9 ) ;
try {
strSummary = summaryDict[ controllerName] ;
if ( strSummary) {
$ ( item) . children ( ".heading" ) . children ( ".options" ) . first ( ) . prepend ( '<li class="controller-summary" style="color:green;" title="' + strSummary + '">' + strSummary + '</li>' ) ;
}
} catch ( e) {
console. log ( e) ;
}
}
} ) ;
}
} ) ;
} catch ( e) {
console. log ( e) ;
}
} ,
_tryTranslate : function ( word ) {
return this . _words[ $. trim ( word) ] !== undefined ? this . _words[ $. trim ( word) ] : word;
} ,
learn : function ( wordsMap ) {
this . _words = wordsMap;
}
} ;
window. SwaggerTranslator. learn ( {
"Warning: Deprecated" : "警告:已过时" ,
"Implementation Notes" : "实现备注" ,
"Response Class" : "响应类" ,
"Status" : "状态" ,
"Parameters" : "参数" ,
"Parameter" : "参数" ,
"Value" : "值" ,
"Description" : "描述" ,
"Parameter Type" : "参数类型" ,
"Data Type" : "数据类型" ,
"Response Messages" : "响应消息" ,
"HTTP Status Code" : "HTTP状态码" ,
"Reason" : "原因" ,
"Response Model" : "响应模型" ,
"Request URL" : "请求URL" ,
"Response Body" : "响应体" ,
"Response Code" : "响应码" ,
"Response Headers" : "响应头" ,
"Hide Response" : "隐藏响应" ,
"Headers" : "头" ,
"Try it out!" : "试一下!" ,
"Show/Hide" : "显示/隐藏" ,
"List Operations" : "显示操作" ,
"Expand Operations" : "展开操作" ,
"Raw" : "原始" ,
"can't parse JSON. Raw result" : "无法解析JSON. 原始结果" ,
"Model Schema" : "模型架构" ,
"Model" : "模型" ,
"apply" : "应用" ,
"Username" : "用户名" ,
"Password" : "密码" ,
"Terms of service" : "服务条款" ,
"Created by" : "创建者" ,
"See more at" : "查看更多:" ,
"Contact the developer" : "联系开发者" ,
"api version" : "api版本" ,
"Response Content Type" : "响应Content Type" ,
"fetching resource" : "正在获取资源" ,
"fetching resource list" : "正在获取资源列表" ,
"Explore" : "浏览" ,
"Show Swagger Petstore Example Apis" : "显示 Swagger Petstore 示例 Apis" ,
"Can't read from server. It may not have the appropriate access-control-origin settings." : "无法从服务器读取。可能没有正确设置access-control-origin。" ,
"Please specify the protocol for" : "请指定协议:" ,
"Can't read swagger JSON from" : "无法读取swagger JSON于" ,
"Finished Loading Resource Information. Rendering Swagger UI" : "已加载资源信息。正在渲染Swagger UI" ,
"Unable to read api" : "无法读取api" ,
"from path" : "从路径" ,
"server returned" : "服务器返回"
} ) ;
$ ( function ( ) {
window. SwaggerTranslator. translate ( ) ;
window. SwaggerTranslator. setControllerSummary ( ) ;
} ) ;
App_Start – SwaggerConfig
public static void Register ( )
{
var thisAssembly = typeof ( SwaggerConfig ) . Assembly;
}
protected static string GetXmlCommentsPath ( string name)
{
return string . Format ( @"{0}\bin\NetFramework.XML" , AppDomain. CurrentDomain. BaseDirectory, name) ;
}