我打电话给网络Api,让我回复了一个回复。首先,我将响应定义为var但不是我返回以定义方法顶部的响应。我不确定我必须使用哪种类型的变量。我使用字典,但我得到的是新的关键字。
无法将类型'AnonymousType#1'隐式转换为Dictionary。
这是我的代码:
[AllowAnonymous]
[Route("searchuser")]
[HttpPost]
public async Task<ActionResult> SearchUser(UserInfo userInfo)
{
object userObject = null;
Dictionary<string, object> respone = new Dictionary<string, object>();
if (userInfo.LastName != null && userInfo.Zip != null && userInfo.Ssn != null)
{
UserKey userKey = new UserKey();
userKey.AccountKey = accessKey;
var response = await httpClient.PostAsJsonAsync(string.Format("{0}{1}", LoanApiBaseUrlValue, "/verifyuser"), userKey);
if (response.IsSuccessStatusCode)
{
userObject = new JavaScriptSerializer().DeserializeObject(response.Content.ReadAsStringAsync().Result) as object;
var json = response.Content.ReadAsStringAsync().Result;
var userVerify = new JavaScriptSerializer().Deserialize<VerifyUser>(json);
}
}
respone = new // this is where I am getting the error before I was using var and it was working.
{
success = userObject != null,
data = userObject
};
return Json(respone, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
在JSON中发送结果可以使用任何类型的变量(List,Dictionary,int,string,...)。
您可以这样做:
public async Task<HttpResponseMessage> SearchUser(UserInfo userInfo) {
HttpResponseMessage response = new HttpResponseMessage();
try
{
object userObject = null;
// Do something
object result = new { success = userObject != null, data = userObject };
response = Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception e)
{
// Do Log
response = Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
}
var tc = new TaskCompletionSource<HttpResponseMessage>();
tc.SetResult(response);
return tc.Task;
}
无论变量的类型如何,您都将以JSON形式返回,在这种情况下,该变量是匿名对象类型。
错误消息&#34;无法隐式转换类型&#39; AnonymousType#1&#39;字典。&#34;是因为您试图将匿名对象类型的值设置为Dictionary类型的变量:
// ...
Dictionary<string, object> respone = new Dictionary<string, object>();
// ...
respone = new // this is where I am getting the error before I was using var and it was working.
{
success = userObject != null,
data = userObject
};