asp.net-core - ASP.NET Core WebAPI 中的 POST 服务
问题描述
我正在尝试在 Visual Studio 中编写非常简单的多平台应用程序(iOS 和 Android)。这个应用程序使用网络服务,上传到我的虚拟主机上。
这是调用 WebAPI(获取和发布)的代码:
async void post_async(object sender, System.EventArgs e)
{
Console.WriteLine("POST");
try
{
HttpClient httpClient = new HttpClient();
var BaseAddress = "https://mywebsite";
var response = await httpClient.PostAsync(BaseAddress, null);
var message = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: " + message);
}
catch (Exception er)
{
Console.WriteLine($"ERROR: " + er.ToString());
}
}
async void get_async(object sender, System.EventArgs e)
{
try
{
HttpClient httpClient = new HttpClient();
var BaseAddress = "https://mywebsite";
var response = await httpClient.GetAsync(BaseAddress);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: " + content);
}
}
catch (Exception er)
{
Console.WriteLine($"ERROR: " + er.ToString());
}
}
这是 Web Api 的非常简单的代码:
[HttpGet]
public ActionResult<string> Get()
{
return "get method ok";
}
[HttpPost]
public ActionResult<string> Post()
{
return "post method ok";
}
非常奇怪的问题,因为对于每个 void 我总是获得“get method ok”。所以“get”是可以的,但我不明白为什么我不能调用 post 方法。我尝试使用 Postman:同样的问题。
我正在使用这个非常简单的代码:
[ActionName("getmet")]
public ActionResult<string> getmet()
{
return "get method ok";
}
[ActionName("postmet")]
public ActionResult<string> postmet()
{
return "post method ok";
}
现在我当然可以调用 https://mywebsite/getmet 或 postmet,它使用邮递员工作。
如果我将 [HttpPost] 用于 postmet 方法,在 Postman 上我会得到“404 not found”。为什么?
解决方案
var BaseAddress = "https://mywebsite"; //
URL 通过 difualt 命中 get 方法,这意味着作为https://mywebsite/Get工作,因为您的实际发布方法 URL 是https://mywebsite/Post
而不是调用不同的方法使用如下代码。
[HttpPost]
[HttpGet]
public ActionResult<string> Get()
{
return "method ok";
}
或者你可以使用 API ROUTE
或者
[AcceptVerbs(HttpVerbs.Get|HttpVerbs.Post)]
推荐阅读
- python - 将正则表达式格式应用于与 pandas 列匹配的术语列表
- android - 当我将 isCloseIconVisible 设置为 false 时的筹码保证金问题
- php - 如果我不知道有多少个数组,如何在 GraphQL 中返回一个数组(PHP,rebing/graphql-laravel)
- angular - Angular 后端 HTTP 请求
- python - Mixture parameters from a TensorFlow Probability mixture density network
- android - 有没有办法同时反编译多个android apk?
- angular - 运行 npm install 时出现 Angular 应用程序错误 - 无法解析依赖项
- html - img 选项卡可见性变为空白
- jointjs - 动态设置纸张模型
- regex - PowerShell 按模式提取