简体   繁体   中英

Setting a parameter to a asp.net WebAPI URL

I have a console app that I'm using to call the CRUD operations of my MVC WebApi Controller.

Currently I have my HTTP request set as follows:

string _URL = "http://localhost:1035/api/values/getselectedperson";

var CreatePersonID = new PersonID
{
    PersonsID = ID
};

string convertedJSONPayload = JsonConvert.SerializeObject(CreatePersonID, new IsoDateTimeConverter());


var httpWebRequest = (HttpWebRequest)WebRequest.Create(_URL);
httpWebRequest.Headers.Add("Culture", "en-US");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "GET";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    streamWriter.Write(convertedJSONPayload);
    streamWriter.Flush();
    streamWriter.Close();
}

return HandleResponse((HttpWebResponse)httpWebRequest.GetResponse());

How do I add the JSON ID parameter to the URL and to be received by my controller 'GetSelectPerson'?

public IPerson GetSelectedPerson(object id)
{
    ....... code
}

You are doing something very contradictory:

httpWebRequest.Method = "GET";

and then attempting to write to the body of the request some JSON payload.

GET request means that you should pass everything as query string parameters. A GET request by definition doesn't have a body.

Like this:

string _URL = "http://localhost:1035/api/values/getselectedperson?id=" + HttpUtility.UrlEncode(ID);

var httpWebRequest = (HttpWebRequest)WebRequest.Create(_URL);
httpWebRequest.Headers.Add("Culture", "en-US");
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "GET";

return HandleResponse((HttpWebResponse)httpWebRequest.GetResponse());

and then your action:

public IPerson GetSelectedPerson(string id)
{
    ....... code
}

Now if you want to send some complex object and use POST, that's an entirely different story.

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