When the scaffold for a .NET core Web API is used it includes:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
in the ConfigureServices
method and
app.UseMvc();
in the Configure method.
Why is this? A web API doesn't need "Model View Controller". It might only need "Model" and "Controller". I relate MVC very much to Views and Razor. Can these declarations be left out?
If we check the source code for the internal AddMvc
extension we can see these things clearly:
public static IMvcBuilder AddMvc(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var builder = services.AddMvcCore();
builder.AddApiExplorer();
builder.AddAuthorization();
AddDefaultFrameworkParts(builder.PartManager);
// Order added affects options setup order
// Default framework order
builder.AddFormatterMappings();
builder.AddViews();
builder.AddRazorViewEngine();
builder.AddRazorPages();
builder.AddCacheTagHelper();
// +1 order
builder.AddDataAnnotations(); // +1 order
// +10 order
builder.AddJsonFormatters();
builder.AddCors();
return new MvcBuilder(builder.Services, builder.PartManager);
}
In my opinion, for Web API, you probably need AddJSONFormatters()
and AddCors()
. However, you would also need AddMvcCore()
. This includes stuff like routing, attributes, filters, result executors, model binders, controllers etc.
Refer to https://codingblast.com/using-web-api-asp-net-core-without-mvc-specific-stuff/
app.UseMvc() tells your app to add MVC to the request execution pipeline. This will ensure that all requests to your web application are routable to the MVC framework, meaning you can use controllers, views and anything else contained within the MVC implementation (action filters etc).
if you don't need view functionality then you
Don't create a web API controller by deriving from the Controller
class. Controller
derives from ControllerBase
and adds support for views
, so it's for handling web pages, not web API requests. There's an exception to this rule: if you plan to use the same controller for both views and APIs, derive it from Controller. The ControllerBase
class provides many properties and methods that are useful for handling HTTP requests.
For more details checkout this link. https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With