Remove from ASP.Net Core Web Api template MVC Razor dependency

Introduction: In this article, I'll describe how to not include MVC / Razor features and packages cases, adding a minimum of dependency to ASP.NET Core Web API project.

 

 

一、MVC   VS WebApi

(1) In earlier versions of ASP.NET, MVC and Web API technology stack is completely separate. Despite sharing many similar concepts between them, but the actual type is different. This is usually a bit awkward when you accidentally reference the wrong namespace, usually results in an error.

(2) In ASP.NET Core, this is no longer a problem: MVC and Web API has been unified, which basically no real difference between MVC and Web API controller in the controller. All your MVC controllers can act as a controller, the controller can also act as a Web API to return the format (such as JSON or XML) data.

(3) That said, if you only need to use the Web API function, then you probably do not need MVC functionality. However, the current default templates included by default but the MVC functionality.

 

Second, the default template

When you Visual Studio templates or create a new MVC project from the command line, you can choose to create an empty ASP.NET Core project, Web API project or MVC Web Application project. If you create an "empty" project, the generated applications are actually super lightweight. It does not depend on any MVC structure, and produces only a very simple "Hello World" in response runtime:

On the other hand, if you choose the "MVC Web app" template, then the template would provide a more "complete" applications for you. If you choose authentication options, in addition to all MVC Razor view templates and configuration, it also can include ASP.NET Core Identity, EF Core and SQL Server Integration:

 

 

 If you choose WebApi template, then creates WebApi application and must contain the MVC dependencies, the simplest version contains a ValuesController.

 

 However, although it looks very simple, but it also adds all the necessary dependencies for creating complete MVC application, namely Razor server-side dependencies. This is because it contains the same throughout the MVC Web application Microsoft.AspNetCore.Mvc package, and calls AddMvc in Startup.ConfigureServices in (). As shown below:

 

 

 

 AddMvc () will be added to the service container pile of various services, some of which are necessary to allow the Web API you use, but some of them (especially those related to Razor services) for Web API is not necessary.

In most cases, Microsoft.AspNetCore.Mvc package is the easiest thing, but sometimes you want to reduce dependence as much as possible, and to reduce the burden API as much as possible. In these scenarios, you may find that only specialized applications MVC add the required packages and services would be useful.

 

Third, add the correct posture dependencies

We "empty" Web application template to start from, and then add the Web API packages needed to it. You need those packages will depend on the desired functionality of your application. By default, Empty ASP.NET Core templates include ApplicationInsights and Microsoft.AspNetCore metadata package, so I'll leave it in the project.

On top of these, I would add MVC.Core package, JSON formatted packages and CORS package:

  •  MVC Core package adds all the necessary MVC type, such as ControllerBase and RouteAttribute, as well as many dependencies, such as Microsoft.AspNetCore.Mvc.Abstractions and Microsoft.AspNetCore.Authorization.
  • JSON formatter package to make sure we can actually render Web API operating results
  • CORS package increases the Cross-Origin Resource Sharing (CORS) support - This is a common requirement Web API, Web API which will host the call of their different client domain.

The final .csproj file should look like:

 

 In order to facilitate my practice I posted the text version of the project file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Cors" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="2.1.0" />
   
  </ItemGroup>

</Project>

 

 After completion of the reduction package, we can now update the Startup file to add our WebApi served.

Fourth, we must add the service in Startup.cs file

In most cases, Web API service will add to the project as simple as calling AddMvc in ConfigureServices method (). However, this method does not require us to increase the number of dependencies. By default, it will add ApiExplorer, Razor view engine, Razor views, TagHelpers and DataAnnotations- Currently we do not have to use (if the latter uses and we'll add it later ApiExplorer DataAnnotations are possible), but now we do not need. Instead, we only need to add about the service:

public void ConfigureServices(IServiceCollection services)
{
    var builder = services.AddMvcCore();
    builder.AddAuthorization();
    builder.AddFormatterMappings();
    builder.AddJsonFormatters();
    builder.AddCors();
}

 This is what we need service, well, now we add the middleware needed.

 

Fifth, add middleware

Adding to the pipe MvcMiddleware very simple. We only need UseMvc () replaces the run "Hello World" middleware on the line. However, please note that we are using a non-parametric version of the method, this version does not add any conventional route to the application. Since this is a Web API, so I will only use routing attributes, so no need to set regular routes.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}

            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});

            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }

 

These are what we need to configure MVC, finally, let us create a controller to see if you can run properly.

 

Sixth, add a MVC controller

An important point to note is that when you create a Web API in this way: You have to use all Controller ControllerBase class as the parent class instead Controller. The latter Microsoft.AspNetCore.Mvc package has been defined but we did not add. Fortunately, it contains the main method of rendering Razor-related, so this is not a problem for us. ControllerBase class contains all the various StatusCodeResult help methods you might use, for example, the following code:

[Route("api/[controller]")]
    public class ValuesController:ControllerBase
    {
        // GET api/values
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(new string[] { "value1", "value2" });
        }
    }

 

Results are as follows:

 

 

 Look! This is a streamlined Web API controller with minimal dependencies.

 

Seven expansion: AddWebApi Extension Methods

 

Finally, comb - our ConfigureServices method looks a bit messy. In this method, we can reduce the confusion Startup.cs class by creating an extension method, as follows:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Internal;

// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
    public static class WebApiServiceCollectionExtensions
    {
        /// <summary>
        /// Adds MVC services to the specified <see cref="IServiceCollection" /> for Web API.
        /// This is a slimmed down version of <see cref="MvcServiceCollectionExtensions.AddMvc"/>
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        /// <returns>An <see cref="IMvcBuilder"/> that can be used to further configure the MVC services.</returns>
        public static IMvcBuilder AddWebApi(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            var builder = services.AddMvcCore();
            builder.AddAuthorization();

            builder.AddFormatterMappings();

            // +10 order
            builder.AddJsonFormatters();

            builder.AddCors();

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

        /// <summary>
        /// Adds MVC services to the specified <see cref="IServiceCollection" /> for Web API.
        /// This is a slimmed down version of <see cref="MvcServiceCollectionExtensions.AddMvc"/>
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        /// <param name="setupAction">An <see cref="Action{MvcOptions}"/> to configure the provided <see cref="MvcOptions"/>.</param>
        /// <returns>An <see cref="IMvcBuilder"/> that can be used to further configure the MVC services.</returns>
        public static IMvcBuilder AddWebApi(this IServiceCollection services, Action<MvcOptions> setupAction)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (setupAction == null) throw new ArgumentNullException(nameof(setupAction));

            where builder = services.AddWebApi();
            builder.Services.Configure(setupAction);

            return builder;
        }

    }
}

Finally, we can use this extension method to organize our ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddWebApi();
}

 

This case looks much cleaner.

 

VIII Summary:

 

This article shows when you do not need to know Razor dependence, how to remove them from the application. It's almost minimizes the Web API that we can use in your application. I know there are many possible methods, however, add additional functionality (such as ApiExplorer) is very easy! Well, today to talk to here. Fortunately, Net Core 3.0 has done this for us, do not know if you can refer to my previous article, you can view the source code.

 

 

 

 

Reference article: https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-net-core/

 

 

Author: Guo Zheng

Source: http: //www.cnblogs.com/runningsmallguo/

This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original article page link in the apparent position.

Guess you like

Origin www.cnblogs.com/runningsmallguo/p/11620464.html