简体   繁体   English

具有简单类型参数的C#Web Api Post方法

[英]C# Web Api Post method with simple type parameters

I'm hoping someone can help. 我希望有人能提供帮助。 I have been asked to write a test application to consume a Web API. 我被要求编写一个使用Web API的测试应用程序。

The method I'm trying to consume, has the following signature: 我尝试使用的方法具有以下签名:

[Transaction]
[HttpPost]
[Route("api2/Token/")]
public ApiToken Token(Guid companyId, DateTime dateTime, string passCode)

I've written a simple C# console application. 我已经编写了一个简单的C#控制台应用程序。 However whatever I send to the API returns with a 404 error message and I can't see what my issue is. 但是,无论我发送给API的什么,都会返回404错误消息,并且看不到我的问题是什么。

My code to consume the API is as follows: 我使用该API的代码如下:

_client.BaseAddress = new Uri("http://localhost:1390");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var companyId = Guid.Parse("4A55A43A-5D58-4245-AD7C-A72300A69865");
var apiKey = Guid.Parse("FD9AEE25-2ABC-4664-9333-B07D25ECE046");
var dateTime = DateTime.Now;

var sha256 = SHA256.Create();
var bytes = Encoding.UTF8.GetBytes(string.Format("{0}:{1:yyyyMMddHHmmss}:{2}", companyId, dateTime, apiKey));
var hash = sha256.ComputeHash(bytes);

var sb = new StringBuilder();
foreach (var b in hash)
{
    sb.Append(b.ToString());
}

try
{
    Console.WriteLine("Obtain an authorisation token");

    var response = await _client.PostAsJsonAsync("api2/Token/", new { companyId = companyId, dateTime = dateTime, passCode = sb.ToString() });

}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

All examples I've googled seem to post an object to a Web API method that accepts an object. 我搜索过的所有示例似乎都将对象发布到接受对象的Web API方法中。 Is it possible to post multiple simple types? 是否可以发布多个简单类型?

I don't think it's possible, from the documentation ( https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api ) 我认为从文档( https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-网络API

They've stated that 他们说

If the parameter is a "simple" type, Web API tries to get the value from the URI. 如果参数是“简单”类型,则Web API会尝试从URI中获取值。

For complex types, Web API tries to read the value from the message body 对于复杂类型,Web API尝试从消息正文中读取值

You can try to use uri parameters instead 您可以尝试使用uri参数代替

var response = await _client.PostAsJsonAsync("api2/Token/{companyId}/{dateTime}/{sb.ToString()}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM