Attila Alan
Attila Alan

Reputation: 75

ASP.NET Web API Get Method- Can i do the same with Post method?

this is a Get method in my controller to make a new user.

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

    string firstTwoo = name.Substring(0, 2);
    string firstThree = surname.Substring(0, 3);

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

And this is the RunAsync method in my Console.

public static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        Console.Write("Your username: ");
        string name = Console.ReadLine();
        Console.Write("Your surname: ");
        string surname = Console.ReadLine();
        Console.Write("Please type a number between 5 and 10: ");
        int 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/test?number=" + number + "&name=" + name
            + "&surname=" + surname);

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

My question is; is it possible to do the same with post method? If it is then how? Thank you very much.

Upvotes: 0

Views: 76

Answers (1)

terbubbs
terbubbs

Reputation: 1512

You can use HttpClientExtensions.PostAsJsonAsync:

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
//for security purposes, I think you should be adding an authorization token to the header like this, but it doesn't look like you have any security in place
client.DefaultRequestHeaders.Add("Authorization"," Bearer " + token);
HttpResponseMessage response = await client.PostAsJsonAsync(uri, object);

In MakeUser set the parameter to the object containing number, name, and surname and check the ModelState.IsValid

EDIT

public class User
{
    public int number { get; set; }

    public string name { get; set; }

    public string surname { get; set; }
}

EDIT 2

From Nick Bailey's comment below:

...in this case there's no reason to use more than one object in the POST. It's generally better OOP practice to minimize the number of parameters to functions by grouping them into logically coherent entities.

Upvotes: 1

Related Questions