ASP.NET Core(兼容2.0&3.0) WebAPI 开启静态网页,设置主页,跨域,Json保持原始大小写,添加MIME

开启静态网页

Startup.Configure:

app.UseStaticFiles();

设置主页

Startup.Configure:

DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
defaultFilesOptions.DefaultFileNames.Clear();
defaultFilesOptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defaultFilesOptions);

重要提示,代码是有顺序的:

UseDefaultFiles-UseStaticFiles-UseMvc

汇总:

Startup.Configure:

            DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
            defaultFilesOptions.DefaultFileNames.Clear();
            defaultFilesOptions.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(defaultFilesOptions);

            app.UseStaticFiles();

            app.UseMvc();

跨域

Startup.Configure:(core 3.0 ConfigureServices中需包含services.AddControllers();)

app.UseCors(corsPolicyBuilder => corsPolicyBuilder.AllowAnyMethod().AllowAnyOrigin());

Json保持原始大小写

Startup.ConfigureServices:

2.0:

services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());

3.0 方案1修改原生方法:

            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.DictionaryKeyPolicy = null;
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

3.0 方案2用NewtonsoftJson替换原生方法:

            services.AddControllers()
            //原生Json服务中文、变量、注释支持差,这里切换为Newtonsoft提供的Json服务,必须引用Microsoft.AspNetCore.Mvc.NewtonsoftJson,引用Newtonsoft.Json此处无效
            .AddNewtonsoftJson(options =>
            {
                //保持Json属性/变量大小写
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                // 忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                // 设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                // 如字段为null值,该字段不会返回到前端
                // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; 
            });

添加MIME

Startup.Configure:

            var provider = new FileExtensionContentTypeProvider();
            provider.Mappings[".osm"] = "application/octet-stream";
            app.UseStaticFiles(new StaticFileOptions()
            {
                ContentTypeProvider = provider
            });

 

你可能感兴趣的:(成长的程序员)