HttpClient通过控制台应用程序C#消耗Web API [英] Httpclient consume web api via console app C#
问题描述
我正在尝试通过使用Httpclient的控制台应用程序使用以下Web api.我被困在如何传递参数中.参数将作为命令行参数来.这是我的Rest api
I am trying to consume the below web api via console app using Httpclient. I am stuck as in how to pass the parameter. The paramter is coming as a command line argument. This is my Rest api
[HttpPost, Route("Test")]
public IHttpActionResult Test(bool sample = false)
{
return Ok();
}
此参数来自命令行参数
/Parameters:sample=true.
这是我在控制台应用程序中解析参数的方式
Here is how I am parsing out the parameter in the console app
static int Main(string[] args)
{
if (args.Length == 0)
{
Console.Error.WriteLine("No action provided.");
return -1;
}
foreach (string param in args)
{
switch (param.Substring(0, param.IndexOf(":")))
{
case "/Action":
action = param.Substring(param.IndexOf(":") + 1);
break;
case "/Parameters":
parameter = param.Substring(param.IndexOf(":") + 1);
break;
}
}
return 0;
}
一旦我得到了这种格式的参数
Once I get my parameter which is in this format
parameter ="sample = true"
parameter = "sample=true"
我正在尝试调用网络api调用,但无法传递参数值.谁能指出我在做什么错
I am trying to invoke the web api call but unable to pass the parameter value. can anybody pin point what I am doing wrong
client.BaseAddress = new Uri(ConfigurationManager.AppSettings.Get("BaseWebApiUrl"));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var apiUrl = GetApiURL();
var Context = new StringContent(JsonConvert.SerializeObject(parameter), Encoding.UTF8, "application/json");
var respFeed = await client.PostAsync(apiUrl, Context);
推荐答案
默认情况下,Web Api中的基本类型参数永远不会绑定到请求的正文.
By default in Web Api basic type parameters are never bound to the body of the request.
如果要强制将 bool
参数与请求正文绑定,则需要使用 FromBodyAttribute
装饰它:
If you want to forcefully bind your bool
parameter with the request body you need to decorate it with FromBodyAttribute
:
[HttpPost, Route("Test")]
public IHttpActionResult Test([FromBody] bool sample = false)
{
return Ok();
}
请注意,即使执行此操作,您的请求也不适用于Web Api.必须以特定格式传递单个基本类型参数.在您的情况下,您的请求正文必须为以下内容:
Be aware that even if you do this your request is not valid for Web Api. A single basic type parameter must be passed with a specific format. In your case your request body must be the following:
=true
一种更好的方法是将您的Action参数转换为一个类:
A better approach is to turn your Action parameter into a class:
public class TestModel
{
public bool Sample { get; set; }
}
[HttpPost, Route("Test")]
public IHttpActionResult Test(TestModel model)
{
return Ok();
}
这样,您将能够将Json对象作为请求正文发送,例如:
This way you will be able to send a Json object as request body, like:
{
"sample": true
}
这是一个如何获得这种结果的小例子:
This is a small example of how you could achieve such a result:
var parameterDictionary = parameter.Split("=").ToDictionary(s => s[0], s => bool.Parse(s[1]));
var json = JsonConvert.SerializeObject(parameterDictionary);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var respFeed = await client.PostAsync(apiUrl, content);
这篇关于HttpClient通过控制台应用程序C#消耗Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!