博客 (102)

异常提示:

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,634

对于不同场景下 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,444

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


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


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,471

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,224

ASP.NET Core 缓存 Caching 提供了包括但不限于以下几种存储方式:

内存缓存:https://xoyozo.net/Blog/Details/aspnetcore-memory-cache

SQL Server 缓存:https://xoyozo.net/Blog/Details/aspnetcore-sql-cache

Redis 缓存:https://xoyozo.net/Blog/Details/aspnetcore-redis-cache

MySQL 缓存:https://xoyozo.net/Blog/Details/aspnetcore-mysql-cache


本文介绍内存缓存

Memory Caching

1.新建一个 ASP.NET Core 项目,选择 Web 应用程序,将身份验证 改为 不进行身份验证。

2.添加引用

Install-Package Microsoft.Extensions.Caching.Memory

3.使用

在 Startup.cs 中 ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    // Add framework services.
    services.AddMvc();
}

然后在

public class HomeController : Controller
{
    private IMemoryCache _memoryCache;
    public HomeController(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    public IActionResult Index()
    {
        string cacheKey = "key";
        string result;
        if (!_memoryCache.TryGetValue(cacheKey, out result))
        {
            result = $"LineZero{DateTime.Now}";
            _memoryCache.Set(cacheKey, result);
        }
        ViewBag.Cache = result;
        return View();
    }
}

这里是简单使用,直接设置缓存。

我们还可以加上过期时间,以及移除缓存,还可以在移除时回掉方法。

过期时间支持相对和绝对。

下面是详细的各种用法。

public IActionResult Index()
{
    string cacheKey = "key";
    string result;
    if (!_memoryCache.TryGetValue(cacheKey, out result))
    {
        result = $"LineZero{DateTime.Now}";
        _memoryCache.Set(cacheKey, result);
        //设置相对过期时间2分钟
        _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromMinutes(2)));
        //设置绝对过期时间2分钟
        _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(2)));
        //移除缓存
        _memoryCache.Remove(cacheKey);
        //缓存优先级 (程序压力大时,会根据优先级自动回收)
        _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
            .SetPriority(CacheItemPriority.NeverRemove));
        //缓存回调 10秒过期会回调
        _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(10))
            .RegisterPostEvictionCallback((key, value, reason, substate) =>
            {
                Console.WriteLine($"键{key}值{value}改变,因为{reason}");
            }));
        //缓存回调 根据Token过期
        var cts = new CancellationTokenSource();
        _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
            .AddExpirationToken(new CancellationChangeToken(cts.Token))
            .RegisterPostEvictionCallback((key, value, reason, substate) =>
            {
                Console.WriteLine($"键{key}值{value}改变,因为{reason}");
            }));
        cts.Cancel();
    }
    ViewBag.Cache = result;
    return View();
}


Distributed Cache Tag Helper

在 ASP.NET Core MVC 中有一个 Distributed Cache 我们可以使用。

我们直接在页面上增加 distributed-cache 标签即可。

<distributed-cache name="mycache" expires-after="TimeSpan.FromSeconds(10)">
    <p>缓存项10秒过期-LineZero</p>
    @DateTime.Now
</distributed-cache>
<distributed-cache name="mycachenew" expires-sliding="TimeSpan.FromSeconds(10)">
    <p>缓存项有人访问就不会过期,无人访问10秒过期-LineZero</p>
    @DateTime.Now
</distributed-cache>

这样就能缓存标签内的内容。


L
转自 LineZero 6 年前
8,420

打开 appsettings.json,添加一项配置(如下方示例中的“SiteOptions”项)

image.png

* 注意,如需配置开发环境与生产环境不同的值,可单独在 appsettings.Development.json 文件中配置不同项,格式层次须一致;


C# 中习惯用强类型的方式来操作对象,那么在项目根目录添加类(类名以 SiteOptions为例),格式与 appsettings.json 中保持一致:

public class SiteOptions
{
    public ERPOptions ERP { get; set; }
    public WeixinOpenOptions WeixinOpen { get; set; }
    public WeixinMPOptions WeixinMP { get; set; }
    public SMSOptions SMS { get; set; }
    public AliyunOSSOptions AliyunOSS { get; set; }

    /// <summary>
    /// 单个文件上传的最大大小(MB)
    /// </summary>
    public int MaxSizeOfSigleFile_MB { get; set; }

    /// <summary>
    /// 单个文件上传的最大大小(字节)
    /// </summary>
    public int MaxSizeOfSigleFile_B => MaxSizeOfSigleFile_MB * 1024 * 1024;

    public class ERPOptions
    {
        public int ChannelId { get; set; }
        public string AppKey { get; set; }
    }
    public class WeixinOpenOptions
    {
        public string AppId { get; set; }
        public string AppSecret { get; set; }
    }
    public class WeixinMPOptions
    {
        public string AppId { get; set; }
        public string AppSecret { get; set; }
    }
    public class SMSOptions
    {
        public string AppKey { get; set; }
    }
    public class AliyunOSSOptions
    {
        public string Endpoint { get; set; }
        public string AccessKeyId { get; set; }
        public string AccessKeySecret { get; set; }
        public string BucketName { get; set; }

        /// <summary>
        /// 格式://域名/
        /// </summary>
        public string CdnUrl { get; set; }
    }
}


在 Startup 中注入 IConfiguration,并在 ConfigureServices() 方法中添加服务(注意使用 GetSection() 映射到自命名的“SiteOptions”项)

image.png


在控制器中使用

在控制器类中键入“ctor”,并按两次 Tab 键,创建构造函数

image.png

在构造函数中注入“IOptions”,并在 Action 中使用

using Microsoft.Extensions.Options;

public class TestController : Controller
{
    private readonly IOptions<SiteOptions> options;

    public TestController(IOptions<SiteOptions> options)
    {
        this.options = options;
    }

    public IActionResult Index()
    {
        return View(options.Value.ERP.ChannelId.ToString());
    }
}


在视图中使用

@using Microsoft.Extensions.Options
@inject IOptions<SiteOptions> options

@options.Value.ERP.ChannelId


xoyozo 6 年前
4,070

本文介绍 ASP.NET 的 Swagger 部署,若您使用 ASP.NET Core 应用程序,请移步 ASP.NET Core Web API Swagger 官方文档:

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio

https://github.com/domaindrivendev/Swashbuckle.AspNetCore


安装

NuGet 中搜索安装 Swashbuckle,作者 Richard Morris


访问

http://您的域名/swagger


配置


显示描述

以将描述文件(xml)存放到项目的 bin 目录为例:

  1. 打开项目属性,切换到“生成”选项卡

  2. 在“配置”下拉框选择“所有配置”

  3. 更改“输出路径”为:bin\

  4. 勾选“XML 文档文件”:bin\******.xml,(默认以程序集名称命名)

  5. 打开文件:App_Start/SwaggerConfig.cs

  6. 取消注释:c.IncludeXmlComments(GetXmlCommentsPath());

  7. 添加方法:

    public static string GetXmlCommentsPath()
    {
        return System.IO.Path.Combine(
            System.AppDomain.CurrentDomain.BaseDirectory,
            "bin",
            string.Format("{0}.xml", typeof(SwaggerConfig).Assembly.GetName().Name));
    }

    其中 Combine 方法的第 2 个参数是项目中存放 xml 描述文件的位置,第 3 个参数即以程序集名称作为文件名,与项目属性中配置一致。

如遇到以下错误,请检查第 2、3、4 步骤中的配置(Debug / Release)

500 : {"Message":"An error has occurred."} /swagger/docs/v1


使枚举类型按实际文本作为参数值(而非转成索引数字)

  1. 打开文件:App_Start/SwaggerConfig.cs

  2. 取消注释:c.DescribeAllEnumsAsStrings();

xoyozo 6 年前
3,876

百度地图天地图
初始化地图var map = new BMap.Map("allmap");var map = new T.Map("allmap");
将覆盖物添加到地图addOverlay(overlay: Overlay)addOverLay(overlay:OverLay)
从 Map 的 click 事件中获取坐标点

map.addEventListener("click", function (e) {

    Point = e.point;

}

map.addEventListener("click", function (e) {

    LngLat = e.lnglat;

}

坐标点new BMap.Point(lng: Number, lat: Number)new T.LngLat(lng: Numbe, lat: Number)
像素点new BMap.Pixel(x: Number, y: Number)new T.Point(x: Number, y: Number)
文本标注
new BMap.Label(content: String, {
    offset: Size,
    position: Point
})
new T.Label({
    text: string, 
    position: LngLat, 
    offset: Point
})
设置文本标注样式
setStyle(styles: Object)每个样式使用单独的 set 方法实现
图像标注
new BMap.Marker(Point, {
    offset: Size,
    icon: Icon,
    enableMassClear: Boolean,
    enableDragging: Boolean,
    enableClicking: Boolean,
    raiseOnDrag: Boolean,
    draggingCursor: String,
    rotation: Number,
    shadow: Icon,
    title: String
})
new T.Marker(LngLat, {
    icon: Icon,
    draggable: boolean,
    title: string,
    zIndexOffset: number,
    opacity: number
})
为图像标注添加文本标注Marker.setLabel(label: Label)

无。

可借用 title(鼠标掠过显示)属性来实现,并通过 Marker.options.title 来获取值

从图像标注获取坐标点Point = Marker.getPosition();
LngLat = Marker.getLngLat();
绘制折线
new BMap.Polyline(points: Array<Point>, {
    strokeColor: String,
    strokeWeight: Number,
    strokeOpacity: Number,
    strokeStyle: String,
    enableMassClear: Boolean,
    enableEditing: Boolean,
    enableClicking: Boolean,
    icons: Array<IconSequence>
})
new T.Polyline(points:Array<LngLat>, {
    color: string,
    weight: number,
    opacity: number,
    lineStyle: string
})
绘制多边形
new BMap.Polygon(points: Array<Point>, {
    strokeColor: String,
    fillColor: String,
    strokeWeight: Number,
    strokeOpacity: Number,
    fillOpacity: Number,
    strokeStyle: String,
    enableMassClear: Boolean,
    enableEditing: Boolean,
    enableClicking: Boolean
})
new T.Polygon(points:Array<LngLat>,{
    color: string,
    weight: number,
    opacity: number,
    fillColor: String,
    fillOpacity: number,
    lineStyle: string
})
设置多边形的点数组Polygon.setPath(points: Array<Point>)Polyline.setLngLats(lnglats: Array<LngLat>)
设置地图视野Map.setViewport(view: Array<Point> | Viewport, viewportOptions: ViewportOptions)Map.setViewport(view: Array<LngLat>)
xoyozo 6 年前
7,830
变量名字段名
官方描述
return_code返回状态码

SUCCESS/FAIL

此字段是通信标识,非交易标识,交易是否成功需要查看 trade_state 来判断

在“统一下单”和“支付结果通知”中,该描述变成了:交易是否成功需要查看 result_code 来判断

result_code业务结果SUCCESS/FAIL
trade_state交易状态

SUCCESS — 支付成功

REFUND — 转入退款

NOTPAY — 未支付

CLOSED — 已关闭

REVOKED — 已撤销(付款码支付)

USERPAYING — 用户支付中(付款码支付)

PAYERROR — 支付失败(其他原因,如银行返回失败)

总的来说,

return_code 是用来判断通信状态的,个人理解在“结果通知”时必为 SUCCESS;

result_code 是用来判断业务结果的,指一次调用接口或回调的动作是否如愿执行成功。如“关闭订单”时关闭成功为 SUCCESS,因参数配置错误、找不到订单号、订单状态不允许关闭等其它关闭失败的情况为 FAIL;

trade_state 是用来判断交易状态的,“交易”是指微信支付订单。


另,在“统一下单”和“支付结果通知”中,return_code 的描述变成了:交易是否成功需要查看 result_code 来判断。不知道是官方笔误,还是真的可以用来判断交易是否成功,因为在调用“统一下单”时是未支付状态,根本没有支付成功的可能。


保险起见,我们在异步收到“结果通知”时,不要相信文档去判断 result_code,应调用“查询订单”,并判断 trade_state

xoyozo 6 年前
7,501

无法向会话状态服务器发出会话状态请求。请确保 ASP.NET State Service (ASP.NET 状态服务)已启动,并且客户端端口与服务器端口相同。如果服务器位于远程计算机上,请检查 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection 的值,确保服务器接受远程请求。如果服务器位于本地计算机上,并且上面提到的注册表值不存在或者设置为 0,则状态服务器连接字符串必须使用“localhost”或“127.0.0.1”作为服务器名称。

无法连接 StateService 的原因有很多种,我遇到的情况是:

VS 中使用 IISExpress 调试项目,系统没有安装 IIS,

ASP.NET 状态服务是开启状态,

没有对系统作任何修改,无缘无故无法连接。


修改注册表、配置防火墙无效(我没有用到远程连接),

执行 aspnet_regiis -i -enables 无效,

重装 .NET Framework 4.8 Developer Pack 无效,

差点就重装系统了。


最终的解决方法是:

在“启用或关闭 Windows 功能”中勾选安装:Internet Information Services -> 万维网服务 -> 应用程序开发功能 -> ASP.NET 4.8

重启系统。

image.png

xoyozo 6 年前
3,892