【问题标题】:What should be the namespace used in ASP.NET Core Web API?ASP.NET Core Web API 中使用的命名空间应该是什么?
【发布时间】:2021-10-26 06:15:37
【问题描述】:

在我的 ASP.NET Core Web API 项目中,我想使用 HttpPost、HttpGet、HttpDelete 等方法。当我将它添加到动作中时,IntelliSense 会建议这三个命名空间:

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

应该使用哪一个?为什么?

【问题讨论】:

  • the manual 有帮助吗?
  • @FranzGleichmann ,我认为不是,因为我的问题是,在 WEB API 上实现 Http 方法时应该使用哪个命名空间?

标签: c# asp.net-core-webapi


【解决方案1】:

Microsoft.AspNetCore.Mvc 是您在 VisualStudio 中创建 Asp.NET Core Web API 时的默认命名空间。无需将您的项目依赖于其他命名空间。
您还可以阅读此文档:
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc?view=aspnetcore-5.0

例如:

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();
        }
    }
}

【讨论】:

  • 我应该使用这个吗?但是我没有像@fatameh 的答案那样的任何视图支持。我只是要在我的第 3 方应用程序上调用这个 API。
  • @LevesqueXylia 是的,如果您只想要 Web API 功能,Microsoft.AspNetCore.Mvc 就足够了。
  • @LevesqueXylia 我也推荐这些教程:tutorialsteacher.com/core 和 tutorialspoint.com/asp.net_core/index.htm,祝你好运。
【解决方案2】:

Microsoft.AspNet.Mvc 和 System.Web.Mvc 完全一样 如果你有 View 支持,那么使用 Mvc,这将支持 Mvc 设计模式

如果不是(您只是调用第三方应用程序),则使用System.Web.Http

看看这个 => What is the different between System.Web.Http.HttpPut Vs System.Web.Mvc.HttpPut

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

【讨论】:

  • 那么,我应该使用System.Web.Http吗?因为我只是要在我的 3rd 方应用程序上调用这个 API?
  • 如果你正在构建一个 web api(我认为你是)使用 Mvc
  • 谢谢这位先生。如果我能接受超过 1 个答案就好了。我也会接受这个。你们都帮我理解了这个命名空间。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 2013-03-11
  • 1970-01-01
  • 2022-12-28
  • 1970-01-01
相关资源
最近更新 更多