【问题标题】:Web Api 2 controller to download wikipedia api and show json output on webWeb Api 2 控制器下载 wikipedia api 并在 web 上显示 json 输出
【发布时间】:2016-01-27 09:19:36
【问题描述】:

我正在尝试解析包含文章短文本的 wikipedia api。我正在使用 ASP.Net MVC 进行编码。我的 wikipedia api 是 https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Berlin&redirects=,它是 json 格式的。目前我所做的是 - 在模型内部创建了一个名为 Wiki 的文件夹,并在其中创建了四个名为 Limits.cs、Pageval.cs、Query.cs、Rootobject.cs 的类。

public class Limits
{
    public int extracts { get; set; }
}

public class Pageval
{
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public string extract { get; set; }
}
 public class Query
{
    public Dictionary<string, Pageval> pages { get; set; }
}

public class Rootobject
{
    public string batchcomplete { get; set; }
    public Query query { get; set; }
    public Limits limits { get; set; }
}

现在在控制器类中,我创建了一个 WebApi 2 控制器来使模型对象显示在网络上。在这种情况下,我对处理这种情况非常陌生,因为我是 MVC 的新手。我正在尝试以这种方式解析,但它根本不起作用。

 public class WikiController : ApiController
  {
    // GET: api/Wiki


    // GET: api/Wiki/5
    public string GetShortText(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 是-

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

【问题讨论】:

  • 你得到什么样的错误?
  • @JoakimSkoog:当我导航到localhost:53423/api/wiki 时,它会显示在网络上。 未找到与请求 URI 'localhost:53423/api/wiki' 匹配的 HTTP 资源。 在控制器“Wiki”上找不到与请求匹配的操作。 错误>。但我只想看到提取的短文本
  • 将 [Route("{name}")] 添加到 GetShortText 方法的顶部。
  • @nowmim21:您可以在问题中包含您的路线配置吗?
  • @JoakimSkoog:我已经编辑并在我的问题下方给出了我的路线配置。

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


【解决方案1】:

你可以做几件事。您可以使用属性路由,也可以为自定义方法定义路由。它目前未映射的原因是您没有定义参数的路线。所以走你可以定义的路线

routes.MapRoute(
            name: "Wiki",
            url: "api/wiki/getshorttext/name",
            defaults: new { controller = "Wiki", action = "GetShortText", name = UrlParameter.Optional }
        )

;

附带说明,当您执行 I/O 绑定操作时,我建议您使用 .net 的 async and await 功能进行操作 async。这样,您在等待 Wikipedia 响应时就不会阻塞任何线程。 HttpClient 还提供了一个 DownloadStringAsync,这是等待的。看看async and await

【讨论】:

  • 我试过了,但它显示 HTTP 错误 403.14 - 禁止。我应该在 routconfig.cs 或 webapiconfig.cs 哪里编辑此代码
  • 这意味着现在路由应该是有效的。检查你的安全?用户是否必须登录等。
  • 好的,这是一个单独的问题。
  • 您可以将登录问题作为单独的问题发布。你在登录时遇到什么错误。
  • 但是登录除外是否获取 json 文件。因为当我尝试使用示例 value1 和 value2 时,它会在网络上显示字符串值 1 和值 2。
猜你喜欢
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多