简体   繁体   中英

ASP.NET Web APi - Passing an object as parameter

MakeUser method in the User controller for creating a username and password.

[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 class for sending the parameters as an object.

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

RunAsync method in console client. Can i pass an object with Get method? If yes what is my mistake here? Thank you!

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 requests don't support you passing objects in this way. The only option is to do it as a query string param as others have already demonstrated. From a design perspective, since you are creating a new resource it makes much more sense for this to be a POST or PUT request which both allow for an actual payload to be sent along with the request.

[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

Your variable p cannot be passed as query string parameter like how you have it. To populate the url and query strings the way you prefer, you would have to write out the rest of the query string and access the object's properties while building the string up.

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

The MakeUser() method will need to look similar to something below:

[HttpGet]
public string MakeUser(string name, string surname, int number) 
{
}

I am not seeing however where you are calling the MakeUser() method. Perhaps in the query string parameter you need to make it 'api/makeuser?'.

You CAN pass the p parameter like you want to, it's perfectly fine, take a look at the FromUri paragraph here where an object is used as a parameter:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

The method takes an object as a parameter, not the indivudual members. You call it by specifying the members though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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