Asp.Net Core MVC和Web API不同

起因

思来想去还是觉得每天学的东西是很好的,坚持下来成为习惯,就更好了.今天来看一下在Asp.Net Core中,MVC和Web API区别有哪些.

MVC和Web API区别


Asp.Net Core MVC和Web API在请求管道的区别
源码位置: /src/Mvc/Mvc/src/MvcServiceCollectionExtensions.cs
MVC使用的是AddControllersWithViews,Web API使用的是AddControllers,从名字看上MVC的功能更多的.实际上也是.下面我们从代码上进行验证.
先看Web API的注册服务的源码:
public static IMvcBuilder AddControllers(this IServiceCollection services, Action<MvcOptions> configure)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    // This method excludes all of the view-related services by default.
    var builder = AddControllersCore(services);
    if (configure != null)
    {
        builder.AddMvcOptions(configure);
    }

    return new MvcBuilder(builder.Services, builder.PartManager);
}


private static IMvcCoreBuilder AddControllersCore(IServiceCollection services)
{
    // This method excludes all of the view-related services by default.
    return services
        .AddMvcCore()
        .AddApiExplorer()
        .AddAuthorization()
        .AddCors()
        .AddDataAnnotations()
        .AddFormatterMappings();
}

源码分析到AddControllerCore中,避免层次太深,容易凌乱.

下面看看MVC的AddControllersWithViews的源码:

public static IMvcBuilder AddControllersWithViews(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    var builder = AddControllersWithViewsCore(services);
    return new MvcBuilder(builder.Services, builder.PartManager);
}

private static IMvcCoreBuilder AddControllersWithViewsCore(IServiceCollection services)
{
    var builder = AddControllersCore(services)  //Web API是也是用AddControllersCore
        .AddViews()                             //注册View(视图相关)
        .AddRazorViewEngine()                   //注册Razor视图引擎
        .AddCacheTagHelper();

    AddTagHelpersFrameworkParts(builder.PartManager);

    return builder;
}

从代码分析得出,MVC和Web API公用了注册Controller(控制器)相关的代码.MVC比Web API的多了View(视图)和Razor视图引擎相关的组件.

秋风 2020-08-18