一直在努力学习API几天,发现它有点困难,但设法通过阅读相当多的帖子来鼓励这个:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,domain,contact,contactname,price,type,TF,CF,RI,MJTopicsID,UserTableID")] Identifier identifier)
{
if (ModelState.IsValid)
{
db.Identifiers.Add(identifier);
db.SaveChanges();
return RedirectToAction("Index");
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"https://api.majestic.com/api/json?app_api_key=KEY&cmd=GetIndexItemInfo&items=1&item0=http://www.majestic.com&datasource=fresh");
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string json2 = reader.ReadToEnd();
MajesticData r = JsonConvert.DeserializeObject<MajesticData>(json2);
}
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "ID", identifier.MJTopicsID);
ViewBag.UserTableID = new SelectList(db.UserTables, "ID", "userIdentity", identifier.UserTableID);
return View(identifier);
}
}
然后我使用http://json2csharp.com/创建模型并将RootObject更改为MajesticData。我在我的I中初始化了表,然后在控制器的[httpPost]创建操作中运行它,尽管创建操作很好并且它将数据提交到标识符表并返回视图,但是没有数据提交给MajesticData模型或其他?
使用保存更新:
public ActionResult ApiCall()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.majestic.com/api/json?app_api_key=KEY&cmd=GetIndexItemInfo&items=1&item0=http://www.majestic.com&datasource=fresh");
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string json2 = reader.ReadToEnd();
Datum newdata = JsonConvert.DeserializeObject<Datum>(json2);
db.Datums.Add(newdata);
db.SaveChanges();
}
}
}
答案 0 :(得分:0)
一旦从json构造MajesticData对象,就会丢弃它。您需要一些代码从中提取数据并将其放在ViewBag中(或将其写在其他地方)。
但我会说,如果ModelState无效,你只会调用API确实很奇怪......