簡體   English   中英

httpclient 調用 webapi 以發布數據不起作用

[英]httpclient call to webapi to post data not working

我需要使用字符串參數對 post 方法進行簡單的 webapi 調用。

下面是我正在嘗試的代碼,但是當在 webapi 方法上遇到斷點時,接收到的值為null

StringContent stringContent = new System.Net.Http.StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(url.ToString(), stringContent);

和服務器端代碼:

 // POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

請幫忙...

如果您想將 json 發送到您的 Web API,最好的選擇是使用模型綁定功能,並使用類而不是字符串。

創建模型

public class MyModel
{
    [JsonProperty("firstName")]
    public string FirstName { get; set; }
}

如果你不使用 JsonProperty 屬性,你可以用小寫駝峰寫屬性,像這樣

public class MyModel
{
    public string firstName { get; set; }
}

然后更改您的操作,將 de 參數類型更改為 MyModel

[HttpPost]
public void Post([FromBody]MyModel value)
{
    //value.FirstName
}

您可以使用 Visual Studio 自動創建 C# 類,在此處查看此答案Deserialize JSON into Object C#

我制作了以下測試代碼

Web API 控制器和視圖模型

using System.Web.Http;
using Newtonsoft.Json;

namespace WebApplication3.Controllers
{
    public class ValuesController : ApiController
    {
        [HttpPost]
        public string Post([FromBody]MyModel value)
        {
            return value.FirstName.ToUpper();
        }
    }

    public class MyModel
    {
        [JsonProperty("firstName")]
        public string FirstName { get; set; }
    }
}

控制台客戶端應用程序

using System;
using System.Net.Http;

namespace Temp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter to continue");
            Console.ReadLine();
            DoIt();
            Console.ReadLine();
        }

        private static async void DoIt()
        {
            using (var stringContent = new StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json"))
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://localhost:52042/api/values", stringContent);
                    var result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                }
            }
        }
    }
}

輸出

Enter to continue

"JOHN"

代碼輸出

備選答案:您可以將輸入參數保留為字符串

[HttpPost]
public void Post([FromBody]string value)
{
}

,並使用 C# httpClient 調用它,如下所示:

var kvpList = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("", "yo! r u dtf?")
};
FormUrlEncodedContent rqstBody = new FormUrlEncodedContent(kvpList);


string baseUrl = "http://localhost:60123"; //or "http://SERVERNAME/AppName"
string C_URL_API = baseUrl + "/api/values";
using (var httpClient = new HttpClient())
{
    try
    {   
        HttpResponseMessage resp = await httpClient.PostAsync(C_URL_API, rqstBody); //rqstBody is HttpContent
        if (resp != null && resp.Content != null) {
            var result = await resp.Content.ReadAsStringAsync();
            //do whatevs with result
        } else
            //nothing returned.
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ResetColor();
    }
}

作為記錄,我嘗試了上面的方法,但無法正常工作!

我無法讓它工作,因為我的 API 在一個單獨的項目中。 哪個好? 不,我在對 Base 項目使用 Startup 類時對控制器進行依賴注入。

您可以通過使用 WebAPI 的配置並使用 Unity 在其中配置依賴注入來解決此問題。 下面的代碼對我有用:

WebApiConfig.cs:

 public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            RegisterUnity();
        }

        private static void RegisterUnity()
        {
            var container = new UnityContainer();

            container.RegisterType<IIdentityRespository, IdentityRespository>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }

我希望它能幫助別人:-)

暫無
暫無

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

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