无法访问ASP.NET Core WebAPI中的删除终结点

时间:2019-08-21 17:53:03

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

我有.net核心Web api,并且能够访问get终结点,但不能访问delete。我如何访问删除端点。我不确定是什么问题?

我尝试了以下

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

1 个答案:

答案 0 :(得分:0)

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

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

enter image description here