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

Att*_*lan 0 c# asp.net asp.net-web-api

用户控制器中的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;
}
Run Code Online (Sandbox Code Playgroud)

UserParameter类,用于将参数作为对象发送.

public class UserParameters
{
    public int Number { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

控制台客户端中的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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jes*_*ter 8

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
Run Code Online (Sandbox Code Playgroud)


小智 5

您的变量 p 不能像您拥有它那样作为查询字符串参数传递。要以您喜欢的方式填充 url 和查询字符串,您必须写出查询字符串的其余部分并在构建字符串时访问对象的属性。

string queryString = "api/user?name="+p.Name+"&surname="+p.Surname+"&number="+p.Number;
HttpResponseMessage response = await client.GetAsync(queryString);
Run Code Online (Sandbox Code Playgroud)

MakeUser() 方法需要类似于以下内容:

[HttpGet]
public string MakeUser(string name, string surname, int number) 
{
}
Run Code Online (Sandbox Code Playgroud)

但是,我没有看到您在哪里调用 MakeUser() 方法。也许在查询字符串参数中,您需要将其设为“api/makeuser?”。