Web-api 控制器以 json 格式从维基百科 api 中提取数据并在网络上显示结果
Web-api controller to extract data from Wikipedia api in json format and show the result on web
在我的项目中,我使用 Json 格式的 3 Wikipedia API 从中提取数据。第一个 API 包含维基百科地点文章的短文本,表示文章的第一段。第二个 API 包含地点的纬度和经度。从第三个 API 我得到了那个地方的页面图像 URL 信息。现在我想使用带有 ASP.Net MVC 的 Web-API 控制器来实现我的代码。我的维基百科-API 的简称是- https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Berlin&redirects=
维基百科 Api 纬度和经度是-
https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&titles=Berlin
到目前为止,我所做的是在模型中创建三个文件夹,分别命名为 ShortText、Image 和 Geo。
在 ShortText 文件夹中,我创建了四个 classes 包含 json 对象并将它们命名为 Limits.cs、Pageval.cs、Query.cs 和 Rootobject.cs
Limits.cs
public class Limits
{
public int extracts { get; set; }
}
Pageval.cs
public class Pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
Query.cs
public class Query
{
public Dictionary<string, Pageval> pages { get; set; }
}
Rootobject.cs
public class Rootobject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
对于纬度和经度,我在名为 Coordinate.cs,GeoQuery.cs,GeoRootobject.cs,PageId,[= 的 Geo 文件夹中创建了 4 个 classes 25=]
public class Coordinate
{
public double lat { get; set; }
public double lon { get; set; }
public string primary { get; set; }
public string globe { get; set; }
}
public class GeoQuery
{
public Dictionary<string, PageId> pages { get; set; }
}
public class GeoRootobject
{
public string batchcomplete { get; set; }
public GeoQuery query { get; set; }
}
public class PageId
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public List<Coordinate> coordinates { get; set; }
}
对于 PageImage,我在名为 ImgPageval.cs、ImgQuery.cs、ImgRootobject.cs、Thumbnail.cs 的图像文件夹中创建了 4 个 classes ,
public class ImgPageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public Thumbnail thumbnail { get; set; }
public string pageimage { get; set; }
}
public class ImgQuery
{
public Dictionary<string, ImgPageval> pages { get; set; }
}
public class ImgRootobject
{
public string batchcomplete { get; set; }
public ImgQuery query { get; set; }
}
public class Thumbnail
{
public string source { get; set; }
public int width { get; set; }
public int height { get; set; }
}
所以现在在控制器内部我创建了一个 Web-API 2 控制器 class 我想用它来编写代码来提取数据-
这里我的代码在 all.It 上不工作不是我想在 web.I 上看到的,而是按以下方式编写了我的代码。但我认为这不是获取数据的正确方法
public class WikiController : ApiController
{
// GET: api/Wiki
public string Get(string Name)
{
string result;
using (WebClient client = new WebClient())
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + Name + "&redirects=");
var responseJson = JsonConvert.DeserializeObject<Rootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;
try
{
Regex regex = new Regex(@".(?<=\()[^()]*(?=\)).(.)");
string.Format("Before:{0}", extract);
extract = regex.Replace(extract, string.Empty);
string result1 = String.Format(extract);
result = Regex.Replace(result1, @"\n", " ");
}
catch (Exception)
{
result = "Error";
}
}
return result;
}
我的 Routconfig 和 webapiconfig class 是-
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
WebApiConfig.cs 是
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
我想在 web-
中通过以下方式获取我的结果
{
"Name": "Burgtor",
"Shorttext": "The Burgtor, built 1444 in late Gothic style, was the northern city gate of Hanseatic Lübeck....
"GeoCoordinates": {
"Longitude": 10.6912,
"Latitude": 53.8738
},
"Images": [
"8AB1DF99.jpg or //Image url"
]
}
我正在努力寻找解决方案来获得这个结果。但由于我是处理 MVC Web Api 控制器的新手。我没有找到 proceed.Also 的正确方法,努力尝试通过 Web api 控制器处理 Url json Web api 的方法。很抱歉这么长的描述。
在有 try catch 块的地方,您可以填写自定义结果 class 和 return。
像这样:
public class GeoCoordinates
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class LocationResult
{
public string Name { get; set; }
public string Shorttext { get; set; }
public GeoCoordinates GeoCoordinates { get; set; }
public List<string> Images { get; set; }
}
然后在您的代码中填写 LocationResult 和 return 它的序列化版本。
var result = new LocationResult();
result.Shorttext = responseJson.query.pages[firstKey].extract;
result.Name = responseJson.query.pages[firstKey].title;
//etc.
return JsonConvert.SerializeObject(result);
导致:
public string Get(string id)
{
using (WebClient client = new WebClient())
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + id + "&redirects=");
var responseJson = JsonConvert.DeserializeObject<Rootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
var result = new LocationResult();
result.Shorttext = responseJson.query.pages[firstKey].extract;
result.Name = responseJson.query.pages[firstKey].title;
//etc.
return JsonConvert.SerializeObject(result);
}
}
在我的项目中,我使用 Json 格式的 3 Wikipedia API 从中提取数据。第一个 API 包含维基百科地点文章的短文本,表示文章的第一段。第二个 API 包含地点的纬度和经度。从第三个 API 我得到了那个地方的页面图像 URL 信息。现在我想使用带有 ASP.Net MVC 的 Web-API 控制器来实现我的代码。我的维基百科-API 的简称是- https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Berlin&redirects=
维基百科 Api 纬度和经度是- https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&titles=Berlin
到目前为止,我所做的是在模型中创建三个文件夹,分别命名为 ShortText、Image 和 Geo。
在 ShortText 文件夹中,我创建了四个 classes 包含 json 对象并将它们命名为 Limits.cs、Pageval.cs、Query.cs 和 Rootobject.cs
Limits.cs
public class Limits
{
public int extracts { get; set; }
}
Pageval.cs
public class Pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
Query.cs
public class Query
{
public Dictionary<string, Pageval> pages { get; set; }
}
Rootobject.cs
public class Rootobject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
对于纬度和经度,我在名为 Coordinate.cs,GeoQuery.cs,GeoRootobject.cs,PageId,[= 的 Geo 文件夹中创建了 4 个 classes 25=]
public class Coordinate
{
public double lat { get; set; }
public double lon { get; set; }
public string primary { get; set; }
public string globe { get; set; }
}
public class GeoQuery
{
public Dictionary<string, PageId> pages { get; set; }
}
public class GeoRootobject
{
public string batchcomplete { get; set; }
public GeoQuery query { get; set; }
}
public class PageId
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public List<Coordinate> coordinates { get; set; }
}
对于 PageImage,我在名为 ImgPageval.cs、ImgQuery.cs、ImgRootobject.cs、Thumbnail.cs 的图像文件夹中创建了 4 个 classes ,
public class ImgPageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public Thumbnail thumbnail { get; set; }
public string pageimage { get; set; }
}
public class ImgQuery
{
public Dictionary<string, ImgPageval> pages { get; set; }
}
public class ImgRootobject
{
public string batchcomplete { get; set; }
public ImgQuery query { get; set; }
}
public class Thumbnail
{
public string source { get; set; }
public int width { get; set; }
public int height { get; set; }
}
所以现在在控制器内部我创建了一个 Web-API 2 控制器 class 我想用它来编写代码来提取数据-
这里我的代码在 all.It 上不工作不是我想在 web.I 上看到的,而是按以下方式编写了我的代码。但我认为这不是获取数据的正确方法
public class WikiController : ApiController
{
// GET: api/Wiki
public string Get(string Name)
{
string result;
using (WebClient client = new WebClient())
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + Name + "&redirects=");
var responseJson = JsonConvert.DeserializeObject<Rootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;
try
{
Regex regex = new Regex(@".(?<=\()[^()]*(?=\)).(.)");
string.Format("Before:{0}", extract);
extract = regex.Replace(extract, string.Empty);
string result1 = String.Format(extract);
result = Regex.Replace(result1, @"\n", " ");
}
catch (Exception)
{
result = "Error";
}
}
return result;
}
我的 Routconfig 和 webapiconfig class 是-
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
WebApiConfig.cs 是
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
我想在 web-
中通过以下方式获取我的结果{
"Name": "Burgtor",
"Shorttext": "The Burgtor, built 1444 in late Gothic style, was the northern city gate of Hanseatic Lübeck....
"GeoCoordinates": {
"Longitude": 10.6912,
"Latitude": 53.8738
},
"Images": [
"8AB1DF99.jpg or //Image url"
]
}
我正在努力寻找解决方案来获得这个结果。但由于我是处理 MVC Web Api 控制器的新手。我没有找到 proceed.Also 的正确方法,努力尝试通过 Web api 控制器处理 Url json Web api 的方法。很抱歉这么长的描述。
在有 try catch 块的地方,您可以填写自定义结果 class 和 return。
像这样:
public class GeoCoordinates
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class LocationResult
{
public string Name { get; set; }
public string Shorttext { get; set; }
public GeoCoordinates GeoCoordinates { get; set; }
public List<string> Images { get; set; }
}
然后在您的代码中填写 LocationResult 和 return 它的序列化版本。
var result = new LocationResult();
result.Shorttext = responseJson.query.pages[firstKey].extract;
result.Name = responseJson.query.pages[firstKey].title;
//etc.
return JsonConvert.SerializeObject(result);
导致:
public string Get(string id)
{
using (WebClient client = new WebClient())
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + id + "&redirects=");
var responseJson = JsonConvert.DeserializeObject<Rootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
var result = new LocationResult();
result.Shorttext = responseJson.query.pages[firstKey].extract;
result.Name = responseJson.query.pages[firstKey].title;
//etc.
return JsonConvert.SerializeObject(result);
}
}