Web-api控制器以json格式从Wikipedia api中提取数据并在Web上显示结果

时间:2016-01-28 09:21:30

标签: asp.net json asp.net-mvc asp.net-web-api asp.net-web-api2

在我的项目中,我使用Json格式的3维基百科API来从中提取数据。第一个API包含维基百科文章的短文,意思是文章的第一段。第二个API包含地点的纬度和经度。从第三个API我得到了那些地方的页面图像URL信息。现在我想使用带有ASP.Net MVC的Web-API Controller实现我的代码。我的Wikipedia-API for shortext是 - https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Berlin&redirects=

Wikipedia Api forLititide and Longitude是 - https://en.wikipedia.org/w/api.php?action=query&format=json&prop=coordinates&titles=Berlin

到目前为止,我所做的是在Model中创建三个文件夹,名为ShortText,Image和Geo。

在ShortText文件夹中,我创建了四个包含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; }
 }

对于Latidute和经度,我在Model中的Geo Folder中创建了4个类,名为Coordinate.cs,GeoQuery.cs,GeoRootobject.cs,PageId,

 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,我在Model中创建了4个类,名为ImgPageval.cs,ImgQuery.cs,ImgRootobject.cs,Thumbnail.cs,

 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; }
 }

所以现在在Controller中我创建了一个Web-API 2 Controller类,我想用它来编写代码来提取数据 -

这里我的代码根本不起作用。它不是我想在网上看到的。我用以下方式编写了我的代码。但我认为这不是获取数据的正确方法

 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类是 -

   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 }
        );
    }
}

我想在网上以下列方式获取我的结果 -

{
 "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控制器。我没有得到正确的方法继续进行。也努力通过web api控制器获得处理Url json web api的方法。很抱歉这么久的描述。

1 个答案:

答案 0 :(得分:0)

如果你有try catch块,你可以填充你的自定义结果类并返回它。

这样的事情:

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并返回该序列化版本。

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);
        }
    }