ASP.NET Core 技巧

开启静态网页

Startup.Configure:

app.UseStaticFiles();

设置主页

Startup.Configure:

DefaultFilesOptions defaultFilesOptions = new efaultFilesOptions();

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:

services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new 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>

转载于:https://www.jianshu.com/p/2c46d5af9eec

猜你喜欢

转载自blog.csdn.net/weixin_34375233/article/details/91071088