簡體   English   中英

如何從 asp.net Web Api 調用 Post Methode

[英]How to call Post Methode from asp.net Web Api

我嘗試使用 HTTP Post 方法將數據添加到我的 API 中。

這是我的 Controller:

[Route("api/[controller]")]
[ApiController]
public class PostAccess : ControllerBase
{
    // POST api/<PostAccess>
    [HttpPost]
    public void Post(UserModel user)
    {
    }
}

public class UserModel
{
    public int UserID { get; set; } = 0;
    public string UserName { get; set; } = "";
    public string UserPassword { get; set; } = "";

}

使用這段代碼,我嘗試添加數據。

        var postData = new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("UserName","Jeremia"),
            new KeyValuePair<string, string>("UserPassword","Jeremia")
        };

        var content = (HttpContent)new FormUrlEncodedContent(postData);
        await client.PostAsync("http://localhost:44355/api/PostAccess", content).ContinueWith(
            (postTask) =>
            {
                postTask.Result.EnsureSuccessStatusCode();
            }
           );
        }

我不知道我做錯了什么。 我很沮喪,因為我搜索了 4 個小時來解決這個問題。

對不起我的英語不好,希望你有一個美好的一天:)

您是否編寫了嘗試在 Post function 中添加數據的代碼?

如果是,您必須通過添加關鍵字“異步”將 function 更改為異步

public async void Post(userModel user)

感謝 mabruk 的回答:這是我的工作解決方案:

發布方法:

    [HttpPost]
    public async Task<ActionResult<RequestModel<UserModel>>> PostUser(UserModel user)
    {
    }

並使用 Postman 我發送 HttpPost 這樣就可以到達 post Method

如果要通過代碼發送,請執行以下操作:

 private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        var requestObj = JsonConvert.SerializeObject(new UserModel()
        {
            UserName = "Jeremia1234",
            UserPassword = "9364"
        });

        var client = new HttpClient();
        var content = new StringContent(requestObj, Encoding.UTF8, "application/json");

        HttpResponseMessage response = await client.PostAsync("https://localhost:44355/api/GetAccess", content);


    }

和 RequestModel

public class RequestModel<RequestDataModel>
{
    public string JwtToken { get; set; }
    public string UserName { get; set; }
    public string UserPassword { get; set; }
    public RequestDataModel request { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM