博客 (145)

异常提示:

HTTP Error 500.31 - ANCM Failed to Find Native Dependencies

Common solutions to this issue:

The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.

Troubleshooting steps:

  • Check the system event log for error messages

  • Enable logging the application process' stdout messages

  • Attach a debugger to the application process and inspect

For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028526


解决方法:

安装对应版本(或最新版本)的 ASP.NET Core Runtime,前往下载:https://dotnet.microsoft.com/download

xoyozo 5 年前
13,760

对于不同场景下 WebP 的使用,我们总结了一些解决方案,如下:

 1、若使用场景是浏览器,可以:

JavaScript 能力检测,对支持 WebP 的用户输出 WebP 图片(https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp

使用 WebP 支持插件:WebPJS:http://webpjs.appspot.com,下载 webpjs-0.0.2.min.js


 2、若使用场景是 App,可以:

Android 4.0 以下 WebP 解析库(https://github.com/alexey-pelykh/webp-android-backport

iOS WebP 解析库(https://github.com/carsonmcdonald/WebP-iOS-example


 3、转换工具:

智图(http://zhitu.tencent.com

iSparta(http://isparta.github.io/



阿里云 OSS 格式转换:https://help.aliyun.com/document_detail/44703.html

腾讯云数据万象格式转换:https://cloud.tencent.com/document/product/460/36543

七牛:https://developer.qiniu.com/dora/api/1279/basic-processing-images-imageview2


x
转自 xiangzhihong 5 年前
5,554

情况:

马甲 App 添加链接 a(域名 A),该页面跳转至页面 b(域名 B),信任域名添加 B。


现象:

无法获取 token,即授权不成功。


原因:

马甲 App 是判断首次打开的域名(即本例中的域名 A)是否在信任域名中。


解决:

将上述两个域名都填到信任域名中,或直接添加链接 b,不使用链接 a 作跳转。


另外提醒:

信任域名是真实的 token,合作域名是临时的 token,区别是权限高低;

配置完域名白名单后,应该重启 App 再测试,因为客户端有缓存。

xoyozo 5 年前
5,250

在解决方案资源管理器中选中要运行的项目,

在:菜单 - 运行 - 运行到手机或模拟器 - Android模拟器端口设置 或 ADB路径设置

image.png

在打开的设置页面中填入 ADB 路径和端口号:

image.png

adb 文件在 HBuilderX 安装目录的 \plugins\launcher\tools\adbs\ 文件夹下。

安卓模拟器端口各模拟器不同,以网易 MuMu 模拟器为例,填入 7555 即可。

xoyozo 6 年前
14,283

本教程教你如何升级 ASP.NET 项目中的 MySql.Data 和服务器安装的 Connector/NET 版本至 8.0.18。


使用 MySQL Application Configuration 升级 MySql.Data

双击打开 .edmx 文件后,解决方案资源管理器上会有 MySQL Application Configuration 的图标。(如果没有,点开“从数据库更新模型”一下即可)

image.png

勾选“Use MySQL with Entity Framework”,安装完成。

image.png

完成后发现,Nuget 中会自动安装或升级下面两个组件:

MySql.Data  8.0.18

MySql.Data.EntityFramework  8.0.18

并且在 Web.config 中会自动添加以下节点:

<system.data>
  <DbProviderFactories>
    <remove invariant="MySql.Data.MySqlClient" />
    <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=8.0.18, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
  </DbProviderFactories>
</system.data>

这段代码使 MySql.Data 8.0.18 的项目能够兼容运行在 Connector/NET 6.10.x 环境中。方便我们挨个升级服务器上的项目。


8.0.18 已经不再需要 MySql.Data.Entity 组件了,可以从 Nuget 中手动卸载。

xoyozo 6 年前
6,773

在数据库连接字符串可设置是否将 tinyint(1) 映射为 bool,否则为 sbyte:

TreatTinyAsBoolean=false/true

tinyint(1) 一般用于表示 bool 型字段,存储内容为 0 或 1,但有时候也用来存储其它数字。

以 Discuz! 的表 pre_forum_post 为例,字段 first 和 invisible 都是 tinyint(1),但 first 只储存 0 和 1,invisible 却有 -1、-5 之类的值。

因此我们一般设置 TreatTinyAsBoolean=false,程序中 first 与 invisible 均以 sbyte 处理。


设置 TreatTinyAsBoolean=true 后,EF 或 EF Core 自动将该类型映射为 bool,方便在程序中作进一步处理。

一旦设置 TreatTinyAsBoolean=true,那么所有查询结果中 tinyint(1) 字段的返回值永远只有 1 和 0(即 True/False),即使真实值为 -1,也返回 1。

因为我们必须在确保所有的 tinyint(1) 类型字段都仅表示布尔值是才设置 TreatTinyAsBoolean=true。

一旦部分 tinyint(1) 类型字段用于存放 0 和 1 以外的数,那么就应该设置 TreatTinyAsBoolean=false。


在数据库优先的项目中,以 TreatTinyAsBoolean=false 生成数据模型后,可将明确为布尔类型的字段改为 bool。列出 MySQL 数据库中所有表所有字段中类型为 tinyint(1) 的字段值


以 .edmx 为例:

在项目中搜索该字段名,在搜索结果中找到 .edmx 文件中的两处。

.edmx 文件中的注释已经表明其包含 SSDL、CSDL、C-S mapping 三块内容,

在 SSDL content 下方找到该字段:

<Property Name="字段名" Type="tinyint" Nullable="***" />

改为

<Property Name="字段名" Type="bool" Nullable="***" />


在 CSDL content 下方找到该属性:

<Property Name="属性名" Type="SByte" Nullable="***" />

改为

<Property Name="属性名" Type="Boolean" Nullable="***" />

在解决方案管理器中展开 .edmx ->库名.tt -> 表名.cs 文件,

将模型类中的属性

public sbyte invisible { get; set; }

改为

public bool invisible { get; set; }

或 sbyte? 改为 bool?。


在 EF Core 中,直接打开对应数据表的 .cs 文件,更改属性类型即可。


相关报错:

错误: 指定的成员映射无效。类型中的成员的类型“Edm.SByte[Nullable=False,DefaultValue=]”与类型中的成员的“MySql.bool[Nullable=False,DefaultValue=]”不兼容。

InvalidOperationException: The property '***' is of type 'sbyte' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

尝试先连接一次能解决此问题(概率),非常的莫名其妙:

using Data.Discuz.db_bbs2021Context dbd = new();
var conn = dbd.Database.GetDbConnection();
conn.Open();
conn.Close();


参考:

https://mysqlconnector.net/connection-options/

https://stackoverflow.com/questions/6656511/treat-tiny-as-boolean-and-entity-framework-4


2023年1月注:本文适用于 Pomelo.EntityFrameworkCore.MySql 6.0,升级到 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'.”

解决方法:https://xoyozo.net/Blog/Details/the-sbyte-property-could-not-be-mapped-to-the-database-type-tinyint-1

xoyozo 6 年前
7,762

* 若无特殊注明,本文中的“手机”包含平板电脑


判断网页是否在移动设备中打开


Web Form:

public static bool IsMobileDevice
{
    get
    {
        return (HttpContext.Current.Request.Browser?.IsMobileDevice ?? false)
            || (HttpContext.Current.Request.UserAgent?.Contains("Mobile") ?? false);
    }
}


ASP.NET Core:

好像还没有找到,可能是因为随着响应式布局的流行以及电脑和手机之间的界线越来越不明朗,取消了这个判断?


判断网页是否在微信浏览器中打开(宽松)


Web Form:

public bool IsInWechat
{
    get
    {
        return HttpContext.Current.Request.UserAgent?.Contains("MicroMessenger") ?? false;
    }
}


ASP.NET Core:

需注入 IHttpContextAccessor

public bool IsInWechat
{
    get
    {
        string ua = httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent];
        return ua?.Contains("MicroMessenger") ?? false;
    }
}


判断网页是否在微信浏览器中打开(严谨)


使用 JS-SDK 网页授权来判断




xoyozo 6 年前
4,583

Nuget 安装:X.PagedList.Mvc.Core


控制器:

using X.PagedList;

public IActionResult Index(int page = 1)
{
    ……
    return View(q.ToPagedList(page, size));
}


视图:

@using X.PagedList
@using X.PagedList.Mvc.Core
@model IPagedList<xxx>

@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))


自定义(options 默认值):

@Html.PagedListPager(
    Model, 
    page => Url.Action("Index", new { page }), 
    new X.PagedList.Mvc.Common.PagedListRenderOptionsBase
    {
        HtmlEncoder = HtmlEncoder.get_Default(),
        DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
        DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded,
        DisplayLinkToPreviousPage = PagedListDisplayMode.IfNeeded,
        DisplayLinkToNextPage = PagedListDisplayMode.IfNeeded,
        DisplayLinkToIndividualPages = true,
        DisplayPageCountAndCurrentLocation = false, // 显示总页数和当前页码
        MaximumPageNumbersToDisplay = 10, // 最多显示页码数
        DisplayEllipsesWhenNotShowingAllPageNumbers = true,
        EllipsesFormat = "&#8230;",
        LinkToFirstPageFormat = "<<",
        LinkToPreviousPageFormat = "<",
        LinkToIndividualPageFormat = "{0}",
        LinkToNextPageFormat = ">",
        LinkToLastPageFormat = ">>",
        PageCountAndCurrentLocationFormat = "Page {0} of {1}.",
        ItemSliceAndTotalFormat = "Showing items {0} through {1} of {2}.",
        FunctionToDisplayEachPageNumber = null,
        ClassToApplyToFirstListItemInPager = null,
        ClassToApplyToLastListItemInPager = null,
        ContainerDivClasses = new string[1]
        {
            "pagination-container"
        },
        UlElementClasses = new string[1]
        {
            "pagination"
        },
        LiElementClasses = Enumerable.Empty<string>(),
        PageClasses = Enumerable.Empty<string>(),
        UlElementattributes = null,
        ActiveLiElementClass = "active",
        EllipsesElementClass = "PagedList-ellipses",
        PreviousElementClass = "PagedList-skipToPrevious",
        NextElementClass = "PagedList-skipToNext",
    })


保留地址栏参数:

@{ 
    string query = Context.Request.QueryString.Value;
}
@Html.PagedListPager(Model, page => Regex.IsMatch(query, @"[?&]page=\d+")
    ? Regex.Replace(query, @"([?&])page=\d+", $"$1page={page}")
    : (query.StartsWith("?") ? $"{query}&page={page}" : $"{query}?page={page}"),
    new X.PagedList.Web.Common.PagedListRenderOptionsBase
    {
        DisplayPageCountAndCurrentLocation = true,
        MaximumPageNumbersToDisplay = 5,
    })

这里从查询字符串中判断并替换 page 值,如果有更简单的方法敬请告知。比如 Webdiyer 的分页组件会自动携带所有参数。


更多使用方式参官方文档:https://github.com/dncuug/X.PagedList


附应用于 Unify Template(一款基于 Bootstrap 的 HTML 模板)中的配置:

<style>
    .u-pagination-v1-1--active .u-pagination-v1-1 { color: #fff; border-color: #72c02c; }
    .PagedList-pageCountAndLocation { float: right !important; }
</style>
@{
    string query = Context.Request.QueryString.Value;
}
@Html.PagedListPager(Model, page => Regex.IsMatch(query, @"[?&]page=\d+")
    ? Regex.Replace(query, @"([?&])page=\d+", $"$1page={page}")
    : (query.StartsWith("?") ? $"{query}&page={page}" : $"{query}?page={page}"),
    new X.PagedList.Web.Common.PagedListRenderOptionsBase
    {
        DisplayPageCountAndCurrentLocation = true,
        MaximumPageNumbersToDisplay = 5,
        UlElementClasses = new string[] { "list-inline" },
        LiElementClasses = new string[] { "list-inline-item" },
        PageClasses = new string[] { "u-pagination-v1__item", "u-pagination-v1-1", "g-pa-7-14" },
        ActiveLiElementClass = "u-pagination-v1-1--active",
        EllipsesElementClass = "g-pa-7-14",
    })


xoyozo 6 年前
10,315

安装 Nuget 包:

BuildBundlerMinifier


项目根目录创建绑定配置文件:bundleconfig.json

示例:

[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    "inputFiles": [
      "wwwroot/css/site.css",
      "wwwroot/css/custom.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "sourceMap": false
  }
]

配置文件中所有路径都相对于项目根目录(而非静态文件根目录 wwwroot),因此配置的路径都要以“wwwroot”开头。

outputFileName 是压缩合并后的文件,inputFiles 是被压缩合并的原始文件集合。

对于 js 配置部分,minify.enabled 配置是否缩小,renameLocals 配置是否修改变量名,sourceMap 配置是否生成 map 映射文件。


引用示例:

<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />

asp-append-version 表示是否在引用路径添加版本参数,可实现在文件有修改时及时在客户端浏览器中生效。


* 注意:有时候“生成”不一定生效,“重新生成”肯定会生效。


更多高级用法请参考官方文档

xoyozo 6 年前
7,791

要将 ASP.NET Core 中的会话存储在 Redis 中,可以按照以下步骤进行操作:

安装必要的 NuGet 包:

首先,确保你已经安装了 Microsoft.Extensions.Caching.StackExchangeRedis 包,这是与 Redis 集成的主要包。

在 Visual Studio 中,你可以使用 NuGet 包管理器控制台执行以下命令:

Install-Package Microsoft.Extensions.Caching.StackExchangeRedis

配置 Redis 连接:

在你的 ASP.NET Core 应用程序的 Startup.cs 文件中,使用 AddStackExchangeRedisCache 方法配置 Redis 连接。在 ConfigureServices 方法中添加以下代码:

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "your_redis_connection_string";
    options.InstanceName = "your_instance_name";
});

请将 "your_redis_connection_string" 替换为你的 Redis 连接字符串,并将 "your_instance_name" 替换为你的 Redis 实例名称。

配置会话中间件:

Startup.csConfigureServices 方法中,使用 AddSession 方法配置会话中间件,并在 Configure 方法中启用它:

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30); // 设置会话超时时间
});

使用会话中间件:

Startup.csConfigure 方法中,在调用 app.UseRouting() 之前添加以下代码来启用会话中间件:

app.UseSession();

在控制器或视图中使用会话:

现在,你可以在控制器或视图中使用会话来存储和检索数据。例如:

// 存储数据到会话
HttpContext.Session.SetString("Key", "Value");

// 从会话中检索数据
var value = HttpContext.Session.GetString("Key");

通过这种方式,你可以将会话数据存储在 Redis 中,而不是默认的内存中。

请确保根据你的应用程序的需求进行适当的配置和安全措施,以确保 Redis 连接的安全性和可靠性。

xoyozo 6 年前
6,574