ASP.NET Core WebAPI 开启静态网页,设置主页,跨域,Json保持原始大小写,添加MIME,解除大文件上传限制

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/fromfire2/article/details/83503883

开启静态网页

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:

app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());

Json保持原始大小写

Startup.ConfigureServices:

<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />

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

添加MIME

Startup.Configure:

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

解除大文件上传限制(做好验证,防攻击)

Program.BuildWebHost:

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().UseKestrel(options =>
            {
                //所有controller都不限制post的body大小
                options.Limits.MaxRequestBufferSize = long.MaxValue;
                options.Limits.MaxRequestBodySize = long.MaxValue;
                //设置超时时间
                options.Limits.KeepAliveTimeout = TimeSpan.MaxValue;
                options.Limits.RequestHeadersTimeout = TimeSpan.MaxValue;
            }).Build();

Startup.ConfigureServices:

            //大文件上传
            services.Configure<FormOptions>(options =>
            {
                options.ValueLengthLimit = int.MaxValue;
                options.BufferBodyLengthLimit = long.MaxValue;
                options.MultipartBoundaryLengthLimit = int.MaxValue;
                options.MultipartBodyLengthLimit = long.MaxValue;
            });

web.config(如果以上代码不起作用,那么再补充配置文件)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location>
    <system.webServer>
      <security>
        <requestFiltering>
          <requestLimits maxAllowedContentLength="1073741822" />
        </requestFiltering>
      </security>
    </system.webServer>
  </location>
</configuration>

 

展开阅读全文

没有更多推荐了,返回首页