我的一个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](显示三个字符串),但是当我尝试将发布请求与 https:// localhost:44312 / GeneratorStatus / 2 一起使用,它给我错误405,并且不返回字符串
答案 0 :(得分:0)
如果您只是在Chrome中更改URL,则可能是问题所在。 405通常意味着您使用了错误的http请求类型。当只是更改URL时,浏览器会对该资源发出GET请求。
您可能想用Postman测试相同的POST方法。
答案 1 :(得分:0)
第一件事
我在这里可能是错的,但是https:// localhost:44312 / GeneratorStatus / 2是我只有在得到东西时才会使用的东西。根据我的经验,我从未见过像这样的POST URL。
第二,
我认为,您做错了Post。首先,希望您使用Postman或curl来测试端点。
您的POST将是这样的。
URL-如果我要发布,则URL为
https://localhost:44312/GeneratorStatus
在您的情况下,Post正文是一个简单的字符串,看起来像这样。
{
input : "some input value"
}
您的控制器可能看起来应该像这样。
[HttpPost]
public List<string> Post(string input)
{
strings.Add(input);
return strings;
}