[英]Setting a parameter to a asp.net WebAPI URL
我有一个控制台应用程序,用于调用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
}
您正在做一些非常矛盾的事情:
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,那就完全不同了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.