我正在尝试将json数据的http请求发送到Web服务。它成功地定向到Web服务,但数据始终为空...
这是我的网络服务:
public bool CheckUserExist ([FromBody] string Email)
{
List<User> all_users = repo.getUsers();
var match = all_users.Find(i => i.Email == Email);
if (match == null)
{
return false;
}
else
{
return true;
}
}
这是我的Http请求:
var webAddr = "http://localhost:59305/api/User/CheckUserExist";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"Email\":\"Email\"}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return RedirectToAction("Index");
}
正如我所提到的...我在Web服务函数中使用调试器...请求被定向到服务但变量“Email”始终为null
答案 0 :(得分:4)
快速解决方法是更改您发布的内容。如果您希望API端点与[FromBody] string Email
一起使用,那么您应该更改“json”:
string json = "\"a@b.c\"";
streamWriter.Write(json);
streamWriter.Flush();
但是,您可能希望在方法上考虑长期的其他一些变化:
HttpWebRequest
有了上述解决方案(首先除了你没有发布你的数据上下文,不想做太多的假设),这里有一些例子可以帮助你入门:
定义共享用户搜索类(在同一项目或共享DLL中共享)
public class UserSearch
{
public string Email { get; set; }
}
让Web API映射针对搜索类
public bool CheckUserExist([FromBody] UserSearch userSearch)
{
IQueryable<User> all_users = repo.getUsers();
var isMatch = all_users.Any(i => i.Email == userSearch.Email);
return isMatch;
}
更改为HttpClient并使用async通过新搜索类发送API请求
public async Task<ActionResult> Check()
{
using (var client = new HttpClient())
{
var search = new UserSearch() { Email = "a@b.c" };
var response = await client.PostAsJsonAsync("http://localhost:59305/api/User/CheckUserExist", search);
if (response.IsSuccessStatusCode)
{
bool exists = await response.Content.ReadAsAsync<bool>();
// Handle what to do with exists
return RedirectToAction("Index");
}
else
{
// Handle unsuccessful call
throw new Exception("Application error");
}
}
}
答案 1 :(得分:1)
您不能使用字符串来接受发布数据,请定义结构类或使用dynamic来接收Json字符串。