博客 (93)

方法一:

在 DbContext.cs 文件中找到 OnConfiguring 方法,添加代码:

#if DEBUG
    optionsBuilder.EnableSensitiveDataLogging();
    optionsBuilder.LogTo(Console.WriteLine); // 输出日志到控制台
    //optionsBuilder.LogTo(message => Debug.WriteLine(message)); // 输出日志到“输出”窗口
#endif

搞定。

若原来是 => 形式的,改为 { } 形式写法即可。


方法二:使用 Logging

打开 DbContext 文件,添加

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Debug;

optionsBuilder.UseMySql

替换为

optionsBuilder.UseLoggerFactory(MyLoggerFactory).UseMySql

添加方法

public static readonly LoggerFactory MyLoggerFactory = new LoggerFactory(new[] {
    new DebugLoggerProvider()
});

即可在“输出”窗口看到生成的 SQL 语句了。


xoyozo 2 年前
1,897

有一个项目,在 VS2022 中正常打开,在 VS2019 中无法加载项目,项目目标框架是 .NET Standard 2.0。报错内容:

error: 无法打开项目文件。 .NET SDK 的版本 7.0.306 至少需要 MSBuild 的 17.4.0 版本。当前可用的 MSBuild 版本为 16.11.2.50704。请将在 global.json 中指定的 .NET SDK 更改为需要当前可用的 MSBuild 版本的旧版本。

解决方法:

运行 Visual Studio Installer,选择 Visual Studio 2019 进行修改,切换到“单个组件”,勾选“.NET SDK (out of support)”,会联动勾选“.NET 5.0 Runtime (Out of support)”与“.NET Core 3.1 Runtime (Out of support)”。

QQ截图20230728135007.png

xoyozo 2 年前
8,289

Pomelo.EntityFrameworkCore.MySql 升级到 7.0 后出现:

System.InvalidOperationException:“The 'sbyte' property could not be mapped to the database type 'tinyint(1)' because the database provider does not support mapping 'sbyte' properties to 'tinyint(1)' columns. Consider mapping to a different database type or converting the property value to a type supported by the database using a value converter. See https://aka.ms/efcore-docs-value-converters for more information. Alternately, exclude the property from the model using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.”

对比 6.0 生成的 DbContext.cs 发现缺少了 UseLoggerFactory,按旧版修改即可。


找到 OnConfiguring 方法,上方插入:

public static readonly LoggerFactory MyLoggerFactory = new LoggerFactory(new[] {
    new DebugLoggerProvider()
});

在 OnConfiguring 方法中将:

optionsBuilder.UseMySql("连接字符串");

改为:

optionsBuilder.UseLoggerFactory(MyLoggerFactory).UseMySql("连接字符串");


xoyozo 2 年前
2,055

LigerShark.WebOptimizer.CoreBuildBundlerMinifier
特点

在运行时捆绑和缩小 CSS 和 JavaScript 文件

具有完整的服务器端和客户端缓存,以确保高性能

可禁用缩小

支持使用通配模式

标记帮助程序与缓存破坏

支持内联

支持 SCSS

将 CSS、JavaScript 或 HTML 文件捆绑到单个输出文件中

保存源文件会自动触发重新捆绑

支持通配模式

支持 CI 方案的 MSBuild 支持

缩小单个或捆绑的 CSS、JavaScript 和 HTML 文件

每种语言的缩小选项是可定制的

打开生成的文件时显示水印

任务运行程序资源管理器集成

命令行支持

快捷更新解决方案中所有捆绑包

禁止生成输出文件

转换为 Gulp

注入(Program.cs)

services.AddWebOptimizer();

app.UseWebOptimizer();


指定捆绑的项目在运行时自动缩小 css 和 js,也可以在 AddWebOptimizer 中自定义。默认情况下,生成的文件不会保存到磁盘,而是保存在缓存中。手动编辑 bundleconfig.json 文件来指定需要合并和缩小的文件
功能配置
{
  "webOptimizer": {
    // 确定是否应设置 HTTP 标头以及是否应支持条件 GET (304) 请求。在开发模式下禁用此功能可能会有所帮助。cache-control
    "enableCaching": true,
    // 确定是否用于缓存。在开发模式下禁用可能会有所帮助。IMemoryCache
    "enableMemoryCache": true,
    // 确定管道资产是否缓存到磁盘。这可以通过从磁盘加载 pipline 资产而不是重新执行管道来加快应用程序重新启动的速度。在开发模式下禁用可能会有所帮助。
    "enableDiskCache": true,
    // 设置资产将存储的目录 ifistrue。必须为读/写。enableDiskCache
    "cacheDirectory": "/var/temp/weboptimizercache",
    // 确定元素是否应指向捆绑路径或应为每个源文件创建引用。这在开发模式下禁用很有帮助。
    "enableTagHelperBundling": true,
    // 是一个绝对 URL,如果存在,它会自动为页面上的任何脚本、样式表或媒体文件添加前缀。注册标记帮助程序后,标记帮助程序会自动添加前缀。在此处查看如何注册标记帮助程序。
    "cdnUrl": "https://my-cdn.com/",
    // 确定捆绑包的源文件中没有内容时的行为,默认情况下,请求捆绑包时将引发 404 异常,设置为 true 以获取包含空内容的捆绑包。
    "allowEmptyBundle": false
  }
}


在 bundleconfig.json 捆绑时设置

[
  {
    "outputFileName": "output/bundle.css",
    "inputFiles": [
      "css/lib/**/*.css", // globbing patterns are supported
      "css/input/site.css"
    ],
    "minify": {
        "enabled": true,
        "commentMode": "all"
    }
  },
  {
    "outputFileName": "output/all.js",
    "inputFiles": [
      "js/*.js",
      "!js/ignore.js" // start with a ! to exclude files
    ]
  },
  {
    "outputFileName": "output/app.js",
    "inputFiles": [
      "input/main.js",
      "input/core/*.js" // all .js files in input/core/
    ]
  }
]


热重载(在开发模式中保存文件自动更新浏览器效果)
VS 安装扩展,方法:菜单 - 扩展 - 管理扩展 - 联机 搜索“Bundler & Minifier
其它资料
ASP.NET 官方文档


xoyozo 3 年前
3,090

以 ASP.NET 6 返回 BadRequestObjectResult 为例。

public IActionResult Post()
{
    return BadRequest("友好的错误提示语");
}


axios

请求示例:

axios.post(url, {})
.then(function (response) {
    console.log(response.data);
})
.catch(function (error) {
    console.log(error.response.data);
});

error 对象:

{
  "message": "Request failed with status code 400",
  "name": "AxiosError",
  "code": "ERR_BAD_REQUEST",
  "status": 400,
  "response": {
    "data": "友好的错误提示语",
    "status": 400
  }
}


jQuery

请求示例:

$.ajax 对象形式

$.ajax({
    url: url,
    type: 'POST',
    data: {},
    success: function (data) {
        console.log(data)
    },
    error: function (jqXHR) {
        console.log(jqXHR.responseText)
    },
    complete: function () {
    },
});

$.ajax 事件处理形式(Event Handlers)jQuery 3+

$.ajax({
    url: url,
    type: 'POST',
    data: {},
})
    .done(function (data) {
        console.log(data)
    })
    .fail(function (jqXHR) {
        console.log(jqXHR.responseText)
    })
    .always(function () {
    });

$.get / $.post / $.delete

$.post(url, {}, function (data) {
    console.log(data)
})
    .done(function (data) {
        console.log(data)
    })
    .fail(function (jqXHR) {
        console.log(jqXHR.responseText)
    })
    .always(function () {
    });

jqXHR 对象:

{
  "readyState": 4,
  "responseText": "友好的错误提示语",
  "status": 400,
  "statusText": "error"
}


xoyozo 3 年前
2,349

本文以 vue 3 为例,vue 2 同理。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>clipboard.js 在 vue.js 中使用</title>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="item in list">
                {{item}}
                <button class="btn-cp" :value="item">复制</button>
            </li>
        </ul>
    </div>
    <script src="//xxx/vue/core-3.x.x/vue.global.js"></script>
    <script src="//xxx/clipboard/clipboard.js-2.x.x/dist/clipboard.min.js"></script>
    <script>
        const app = Vue.createApp({
            data: function () {
                return {
                    list: ["aaa", "bbb", "ccc"]
                }
            },
            mounted: function () {
                var clipboard = new ClipboardJS('.btn-cp', {
                    text: function (trigger) {
                        return trigger.getAttribute('value');
                    }
                });
                clipboard.on('success', function (e) {
                    alert('已复制“' + e.text + '”到粘贴板');
                    e.clearSelection();
                });
            }
        });
        const vm = app.mount('#app');
    </script>
</body>
</html>


xoyozo 3 年前
2,082

开发环境正常,发布到 IIS 报错

Could not load file or assembly 'Microsoft.EntityFrameworkCore.Relational, Version=6.0.x.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. 系统找不到指定的文件。

尝试在 UI 层安装 Pomelo.EntityFrameworkCore.MySql 无果。

最终,在发布时文件发布选项中,去掉“启用 ReadyToRun 编译”就正常了。

当然这种情况不是在所有启用了 ReadyToRun 编译的项目中遇到,但该项目改为不启用 ReadyToRun 后恢复正常了,原因暂时未知。

xoyozo 3 年前
3,571

您需要将 IWebHostEnvironment 注入到类中才能访问属性值 ApplicationBasePath:阅读有关依赖关系注入的信息。成功注入依赖项后,wwwroot 路径应该可供您使用。例如:

private readonly IWebHostEnvironment _appEnvironment;

public ProductsController(IWebHostEnvironment appEnvironment)
{
   _appEnvironment = appEnvironment;
}

用法:

 [HttpGet]
 public IEnumerable<string> Get()
 {
    FolderScanner scanner = new FolderScanner(_appEnvironment.WebRootPath);
    return scanner.scan();
 }

编辑:在 ASP.NET 的更高版本中,IHostingEnvironment 已被替换为 IWebHostEnvironment

O
转自 Oluwafemi 3 年前
3,998
  1. 项目 - 属性 - 生成 - 输出 - 文档文件,勾选“生成包含 API 文档的文件。”,“XML 文档文件路径”可留空。

    image.png

  2. 在配置方法 AddSwaggerGen 中添加以下两行

    var xmlFilename = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));

参:Swashbuckle 和 ASP.NET Core 入门 | Microsoft Docs

xoyozo 3 年前
3,151
public static class EntityFrameworkCoreExtension
{
    private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection connection, params object[] parameters)
    {
        var conn = facade.GetDbConnection();
        connection = conn;
        conn.Open();
        var cmd = conn.CreateCommand();
        cmd.CommandText = sql;
        cmd.Parameters.AddRange(parameters);
        return cmd;
    }

    public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters)
    {
        var command = CreateCommand(facade, sql, out DbConnection conn, parameters);
        var reader = command.ExecuteReader();
        var dt = new DataTable();
        dt.Load(reader);
        reader.Close();
        conn.Close();
        return dt;
    }

    public static List<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new()
    {
        var dt = SqlQuery(facade, sql, parameters);
        return dt.ToList<T>();
    }

    public static List<T> ToList<T>(this DataTable dt) where T : class, new()
    {
        var propertyInfos = typeof(T).GetProperties();
        var list = new List<T>();
        foreach (DataRow row in dt.Rows)
        {
            var t = new T();
            foreach (PropertyInfo p in propertyInfos)
            {
                if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value)
                {
                    p.SetValue(t, row[p.Name], null);
                }
            }
            list.Add(t);
        }
        return list;
    }
}

调用示例:

var data = db.Database.SqlQuery<List<string>>("SELECT 'title' FROM `table` WHERE `id` = {0};", id);


转自 我的个去 3 年前
2,368