【问题标题】:Unable to access the delete endpoint in asp.net core webapi无法访问 asp.net core webapi 中的删除端点
【发布时间】:2019-12-27 01:01:31
【问题描述】:

我有 .net core web api 并且能够访问获取端点但不能访问删除。我如何访问删除端点。我不确定是什么问题?

我已经尝试了以下

http://localhost:53538/api/cities/delete-city/1

我一直在使用 get 端点。

http://localhost:53538/api/cities

控制器

 public class CitiesController : Controller
    {
        private readonly ICityInfoService _cityInfoService;

        public CitiesController(ICityInfoService cityInfoService)
        {
            _cityInfoService = cityInfoService;
        }

        [HttpGet]
        public IActionResult GetCities()
        {
            var cities = _cityInfoService.GetCities();

            if (!cities.Any())
                return NoContent();

            var citiesMapped = cities.Select(MapCity);

            return Ok(citiesMapped);
        }

        [HttpGet("{cityId:int}")]
        public IActionResult GetCity(int cityId)
        {
            try
            {
                var city = _cityInfoService.GetCity(cityId);
                var cityMapped = MapCity(city);

                return Ok(cityMapped);
            }
            catch (CityNotFoundException e)
            {
                return BadRequest(e.Message);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpDelete("delete-city/{cityId:int}")]
        public IActionResult DeleteCity(int cityId)
        {
            try
            {
                _cityInfoService.DeleteCity(cityId);

                return Ok();
            }
            catch (CityNotFoundException e)
            {
                return BadRequest(e.Message);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        private static CityDto MapCity(City city)
        {
            return new CityDto
            {
                Id = city.Id,
                Description = city.Description,
                Name = city.Name
            };
        }
    }

【问题讨论】:

  • 您的路由配置是什么?如果您在 localhost 上使用 IIS?

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


【解决方案1】:

你的删除方法是一个HttpDelete,所以它需要DELETE请求。如果您尝试通过浏览器访问端点,它将无法正常工作,因为它只会执行 GET。

您可以使用 Curl 或 Postman 向您的 URL 发出 DELETE 请求。

【讨论】:

猜你喜欢
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 2019-08-30
相关资源
最近更新 更多