天天看点

【小5聊】.net core 3.1 配置MVC路由和API

微软的core技术更新换代真够快的,从.net framework开始到core,还没来得及熟悉有更新。每次技术或框架的更新,避免不了类和方法的变动,不得不又重新调整框架代码,版本更新快淘汰也快,截至2022年11月3日,core2.1、core5.0都不再支持维护。

拥抱变化,才能紧跟技术前沿

1、启动类代码

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace Core31
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}      

 2、配置服务方法

添加MVC视图和API组件

//===配置MVC-视图===
services.AddControllersWithViews(options =>
{
    options.Filters.Add(typeof(ExceptionFilter)); //全局异常过滤
});

//===配置MVC-API===
services.AddControllers();      

3、配置方法

启动MVC,特别要主要记得加上app.UserRouting()方法,否则可能还是会报错

// 配置MVC视图
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Test}/{action=Index}/{id?}");
});

//===配置MVC-API===
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});      

4、版本下载地址

【小5聊】.net core 3.1 配置MVC路由和API

5、版本支持说明

6、遇到异常信息

// If using Kestrel:
services.Configure<KestrelServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

// If using IIS:
services.Configure<IISServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});      

继续阅读