将参数设置为asp.net WebAPI URL

时间:2013-11-07 15:41:42

标签: c# asp.net-web-api httprequest

我有一个控制台应用程序,我用它来调用我的MVC WebApi控制器的CRUD操作。

目前我的HTTP请求设置如下:

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());

如何将JSON ID参数添加到URL并由我的控制器'GetSelectPerson'接收?

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

1 个答案:

答案 0 :(得分:3)

你正在做一些非常矛盾的事情:

httpWebRequest.Method = "GET";

然后尝试向请求主体写入一些JSON有效负载。

GET请求意味着您应该将所有内容作为查询字符串参数传递。根据定义,GET请求没有正文。

像这样:

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());

然后你的行动:

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

现在,如果你想发送一些复杂的对象并使用POST,那就完全不同了。