Levesque Xylia
Levesque Xylia

Reputation: 369

What should be the namespace used in ASP.NET Core Web API?

In my ASP.NET Core Web API project, I want to use methods like HttpPost, HttpGet, HttpDelete. When I've added that onto the action, IntelliSense suggests these three namespaces:

System.Web.Mvc 
System.Web.Http
Microsoft.AspNetCore.Mvc

Which one should be used and why?

Upvotes: 1

Views: 2344

Answers (2)

Milad Dastan Zand
Milad Dastan Zand

Reputation: 1078

The Microsoft.AspNetCore.Mvc is the default namespace when you create an Asp.NET Core Web API in VisualStudio. There is no need to depend on your project on other namespaces.
You can also read this document:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc?view=aspnetcore-5.0

for example :

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CoreWebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

Upvotes: 1

Fatemeh Mansoor
Fatemeh Mansoor

Reputation: 565

Microsoft.AspNet.Mvc and System.Web.Mvc are exactly the same if you have View support, then use Mvc, This will support Mvc Design pattern

if not (you are simply calling third party apps) then use System.Web.Http

Take a look at this => What is the different between System.Web.Http.HttpPut Vs System.Web.Mvc.HttpPut

and this => For MVC 4, what's the difference between Microsoft.AspNet.Mvc and System.Web.Mvc?

Upvotes: 1

Related Questions