【问题标题】:WebAPI not accepting Post Requests SuccessfullyWebAPI 未成功接受 Post 请求
【发布时间】:2020-09-25 18:59:30
【问题描述】:

我的一个 WebAPI 的控制器昨天运行良好,但今天我对实际控制器代码之外的项目进行了一些更改,现在 API 无法正确发布。这是我的代码:

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

namespace SanTool_WebAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class GeneratorStatusController : ControllerBase
    {
        static List<string> strings = new List<string>()
        {
            "value0", "value1", "value2"
        };

        [HttpGet]
        public List<string> GetValues()
        {
            return strings;
        }

        [HttpPost("{input}")]
        public List<string> Post(string input)
        {
            strings.Add(input);
            return strings;
        }
    }
}

当我使用 IIS 资源管理器运行代码,然后导航到 https://localhost:44312/GeneratorStatus/ 时,它会正确显示我的 [HttpGet](显示三个字符串),但是当我尝试将 post 请求与 https://localhost:44312/GeneratorStatus/2 一起使用,它给了我错误 405 并且不返回字符串

【问题讨论】:

    标签: c# post asp.net-web-api http-post


    【解决方案1】:

    如果您只是在 chrome 中更改 URL,这将是问题所在。 405 通常意味着您使用了错误的 http 请求类型。当只是更改 URL 时,浏览器会向该资源发出 GET 请求。

    您可能希望使用 Postman 测试相同的 POST 方法。

    另见:Asp.Net Core 3.1 405 Method Not Allowed

    【讨论】:

      【解决方案2】:

      第一件事。

      我在这里可能是错的,但 https://localhost:44312/GeneratorStatus/2 是我只会在我得到东西时使用的东西。根据我的经验,我从未见过这样的 POST URL。

      第二,

      我认为,你做错了。首先,我希望您使用 Postman 或 curl 来测试您的端点。

      你的 POST 应该是这样的。

      URL - 如果我在发布,则 URL 将是

      https://localhost:44312/GeneratorStatus
      

      在您的情况下,Post Body 是一个简单的字符串,看起来像这样。

      {
        input : "some input value"
      }
      

      你的控制器应该看起来像这样。

          [HttpPost]
          public List<string> Post(string input)
          {
              strings.Add(input);
              return strings;
          }
      

      【讨论】:

        猜你喜欢
        • 2018-11-13
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        • 2018-09-07
        • 2018-08-14
        • 2018-08-23
        • 1970-01-01
        相关资源
        最近更新 更多