gpt4 book ai didi

c# - ASP.NET Web APi - 将对象作为参数传递

转载 作者:行者123 更新时间:2023-12-05 08:14:02 26 4
gpt4 key购买 nike

用户 Controller 中的 MakeUser 方法,用于创建用户名和密码。

[HttpGet]
public string MakeUser(UserParameters p)
{
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string pass = "";
Random r = new Random();
for (int i = 0; i < p.Number; i++)
{
pass += chars[r.Next(0, 62)];
}

string firstTwoo = p.Name.Substring(0, 2);
string firstThree = p.Surname.Substring(0, 3);

return "Your username is: " + firstTwoo + firstThree + "\nYour password is: " + pass;
}

用于将参数作为对象发送的 UserParameter 类。

public class UserParameters
{
public int Number { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}

控制台客户端中的 RunAsync 方法。我可以使用 Get 方法传递对象吗?如果是的话,我的错误是什么?谢谢!

static async Task RunAsync()
{
using (var client = new HttpClient())
{
var p = new UserParameters();

Console.Write("Your username: ");
p.Name = Console.ReadLine();
Console.Write("Your surname: ");
p.Surname = Console.ReadLine();
Console.Write("Please type a number between 5 and 10: ");
p.Number = int.Parse(Console.ReadLine());

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

//HTTP GET
HttpResponseMessage response = await client.GetAsync("api/user?p=" + p);

if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<UserParameters>();
Console.WriteLine("\n*****************************\n\n" + result);
}
}
}

最佳答案

GET 请求不支持您以这种方式传递对象。唯一的选择是像其他人已经演示的那样将其作为查询字符串参数来执行。从设计的角度来看,由于您正在创建一个新资源,因此将其作为 POSTPUT 请求更有意义,它们都允许发送实际有效负载连同请求。

[HttpPost]
public string MakeUser([FromBody]UserParameters p)
{
...
}

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.PostAsJsonAsync(new Uri("http://localhost:4688/"), p);
// do something with response

关于c# - ASP.NET Web APi - 将对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34819251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com