【发布时间】: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