gpt4 book ai didi

json - 如何在 Controller 中调用 web api 并返回 View MVC4

转载 作者:行者123 更新时间:2023-12-04 15:13:08 25 4
gpt4 key购买 nike

我有一个使用MVC4的项目,我想问一下如何从webapi获取数据并返回到 View 中。

型号

public class Name
{
public Int32 NameId { get; set; }
public String FirstName{ get; set; }
public String LastName{ get; set; }
public String CreatedBy { get; set; }
}

public class IListMyProject
{
public List<Name> Names { get; set; }
}

我可以在我的 Index.cshtml 中列出所有内容使用此代码
public ActionResult Index()
{
string securityToken = repo.GetTokens();
if (securityToken != null)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/Get?$orderby=LastName&$top=10");
string authHeader = System.Net.HttpRequestHeader.Authorization.ToString();
httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken));
var response = client.SendAsync(httpRequestMessage)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode())
.Result;
if (response.IsSuccessStatusCode)
{
model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList();

}
}
return View("Index", model);
}

我可以回复我的观点。现在我有另一个名为 Details.cshtml 的 View ,其中包含以下代码:
 public ActionResult Details(string id)
{
string securityToken = repo.GetTokens();
if (securityToken != null)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/GetById/"+id+"");
string authHeader = System.Net.HttpRequestHeader.Authorization.ToString();
httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken));

var response = client.SendAsync(httpRequestMessage)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode())
.Result;
if (response.IsSuccessStatusCode)
{

model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList();

}
}
return View(model);
}

对于此 Detail,我的 Json 如下所示:
 application/json, text/json
{
"NameId": 1,
"FirstName": "This is First Name",
"LastName": "This is Last Name",
"CreatedBy": "This is Created By"
}

当我运行它时,我收到此错误:
 Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[Models.Name]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'NameId', line 1, position 10.

我该如何解决这个问题,我是 webapi 的新手。我想知道为什么如果我列出所有(对于索引,我使用 api/get)它可以工作,但是当我想详细显示它时,它不起作用。

感谢帮助

问候

编辑

当我调试
 model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList();

它说 Null,当我尝试获得响应时有什么问题吗?

最佳答案

问题是:

{
"NameId": 1,
"FirstName": "This is First Name",
"LastName": "This is Last Name",
"CreatedBy": "This is Created By"
}

不能反序列化为 IList。您上面的 JSON 只是一个名称,而不是名称的集合。所以 Json.NET 反序列化会失败。

确保您的 Web API Controller 返回一个 IList,或者更改您的 MVC 代码以将内容作为单个名称读取。 JSON 中的名称集合看起来像这样:
[{
"NameId": 1,
"FirstName": "This is First Name",
"LastName": "This is Last Name",
"CreatedBy": "This is Created By"
},
{
"NameId": 2,
"FirstName": "This is First Name",
"LastName": "This is Last Name",
"CreatedBy": "This is Created By"
}]

关于json - 如何在 Controller 中调用 web api 并返回 View MVC4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com