Skip to content

在 AspNetCore 上使用 Swifter.Json。

陈鑫伟 edited this page May 20, 2019 · 6 revisions

Swifter.Json 提供高性能,高并发,小分配的 Json 解析功能;非常适合服务器。

相比 2.1 MVC 使用的 Newtonsoft.Json 和 3.0 MVC 使用的 System.Text.Json;性能分别快 5x 和 4x。

首先从 Nuget 上引入最新版的 Swifter.Extensions.AspNetCore 包。

然后在 Startup 中的 ConfigureServices 方法里加入如下代码。

services.ConfigureJsonFormatter();

以下是一个新建的 3.0 MVC 项目中的 Startup 文件。

此文件仅做了将 Swifter.Json 为默认 Json 解析工具的操作。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Swifter.Test.AspNetCore3_0
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
            });


            services.AddControllersWithViews()
                // 代码重点:
                .ConfigureJsonFormatter();

            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}