首页 > 解决方案 > 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”。为什么?

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

解决方案


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)]

推荐阅读