【问题标题】:Web-api controller to extract data from Wikipedia api in json format and show the result on webWeb-api 控制器以 json 格式从 Wikipedia api 中提取数据并在 web 上显示结果
【发布时间】:2016-01-28 09:21:29
【问题描述】:

在我的项目中,我使用 3 个 Json 格式的 Wikipedia API 来从中提取数据。第一个 API 包含 Wikipedia 文章的简短文本,表示文章的第一段。第二个 API 包含地点的纬度和经度。从第三个 API 我得到了那个地方的页面图像 URL 信息。现在我想使用带有 ASP.Net MVC 的 Web-API 控制器来实现我的代码。我的 Wikipedia-API for shortext 是-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 文件夹中,我创建了四个包含 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; }
}

查询.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; }
 }

对于纬度和经度,我在模型中的 Geo 文件夹中创建了 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,我在名为 ImgPageval.cs、ImgQuery.cs、ImgRootobject.cs、Thumbnail.cs 的模型内的图像文件夹内创建了 4 个类,

 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 控制器类,我想用它来编写代码以提取数据-

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

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

   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的方法。抱歉这么长的描述。

【问题讨论】:

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


    【解决方案1】:

    如果你有 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);
            }
        }
    

    【讨论】:

    • 我有一个问题,在这种情况下我不需要实现对Rootobject的反序列化吗?我会直接得到你在代码中提到的所有信息
    • 您能否再解释一下,我应该在哪里实现您的代码。我是处理 MVC 的新手。如果你能详细解释一下就更好了。
    • 如果你把我提供给你的代码放在你有 try {} catch {} 块的地方。逻辑将是这样的:加载页面 - 反序列化为 RootObject 类 - 转换为您的位置结果类 - 返回序列化版本。这样,它将与您在结果示例中得到的结果相同。
    • 那么字符串结果呢。修改代码时我什么也没得到。我尝试实现但显示很多错误
    • 您有 public string Get(string Name),将其更改为 public string Get(string id),因为 WebApiConfig 配置为搜索名为 id 的参数。我已经使用 Get 函数编辑了帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2016-03-22
    • 2021-03-07
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多