3

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);
 }
 }
}
Cellcon
1,2952 gold badges12 silver badges30 bronze badges
asked Jan 15, 2016 at 20:21
1
  • 1
    you cannot pass an object in a GET method, as model binding is not supported, at least not by default Commented Jan 15, 2016 at 20:26

3 Answers 3

15

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
answered Jan 15, 2016 at 20:29

5 Comments

Thanx Jesse, and how can i put the result in Console.WriteLine? Because i can do with Post method but i can not show the result.
You should be able to do it exactly the same as with the GET. Nothing about Console changes just because its a POST instead of GET.
It gives error -response {StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { X-SourceFiles: =?UTF-8?B?RDpcQnVyZWF1YmxhZFxIZXJoYWxpbmdzb2VmZW5pbmdlbjJXZWJBUElcSGVyaGFsaW5nc29lZmVuaW5nZW4yV2ViQVBJ?= Cache-Control: private Date: 2016年1月15日 20:52:58 GMT Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Content-Length: 5412 Allow: GET Allow: HEAD Allow: OPTIONS Allow: TRACE Content-Type: text/html; charset=utf-8 }} System.Net.Http.HttpResponseMessage
Thanx Jesse. After i did shut down it works like a charm.
@AttilaAlan No problem, feel free to upvote or mark as answer if you found this helpful
5

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?'.

answered Jan 15, 2016 at 20:26

2 Comments

Thanx Chad thats the answer
What if object has many property. i.e. UserParameter is very big one. Querystring willbe very long.
4

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://learn.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.

answered Nov 7, 2017 at 10:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.