【发布时间】:2018-06-19 13:53:19
【问题描述】:
我正在编写一个非常轻量级的 Web api 来呈现小型日志文件数据。 不涉及数据库。它必须基于Kestral。 (可选的 IIS)。数据不需要删除或编辑,它只是关于查看数据。并且根据客户端请求,它应该生成原始数据或将 html 格式置于其上,以便能够通过显示可点击的日志文件名(点击日志文件并查看其内容)更深入地研究日志文件。
我对.net core 很陌生,所以我有疑问,显然我在这里做错了,我试图根据客户端功能做出响应,但没有成功。
即使在尝试强制执行 HTML 编码时,我仍然会收到纯文本回复,这对于 telnet(直接 api 调用)是可以的,但在 Firefox/chrome/Edge 中,我需要做些什么额外的事情吗? 让它在网络浏览器中作为 HTML 回复工作
所以我写了一个像这样的 ASP netcore 程序:
<!-- begin snippet: js hide: true --> //code collaps ?
namespace Dataview //this is the file : program.cs
{
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
var hostUrl = configuration["hosturl"];
if (string.IsNullOrEmpty(hostUrl)) hostUrl = "http://192.168.10.60:9000";
string port = hostUrl.Split(":")[2];
System.Diagnostics.Process.Start("cmd", "/C netsh advfirewall firewall add rule name=\"Http Logger Port\" dir=in action=allow protocol=TCP localport="+port);
BuildWebHost(args, hostUrl).Run();
}
public static IWebHost BuildWebHost(string[] args, string hostUrl) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseUrls(hostUrl).UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
}
我的价值控制器程序 ValuesController.cs 看起来像:
namespace Dataview.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
const string LogFolder = @"C:\Data\Count";
String[] result = Directory.GetFiles(LogFolder);
// GET api/values
[HttpGet]
public string Get()//System.Net.Http.HttpResponseMessage Get()
{
var sb = new System.Text.StringBuilder();
sb.Append("<html><body>"); //trying to enforce HTML decoration=> doesnt work
for (int i = 0; i < result.Length; i++)
{
sb.Append($"<div><a href='{Url.Link("DefaultApi", new { Action = "", id = i })}'>{Path.GetFileName(result[i])}</div>");
}
sb.Append("</body></html>");
string answer = sb.ToString();
for (int i = 0; i < result.Length; i++) result[i] = Path.GetFileName(result[i]);
return answer;
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
string[] lines = System.IO.File.ReadAllLines(result[id]);
string answer = "Showing : " + result[id] + "\n" + string.Join('\n', lines);
return answer;
}
=== 更新 ===
我设法通过更改控制器代码获得了 Json 结果,但是显示的列表也不能点击(也没有 HTML 装饰):
[Route("api/[controller]")]
public class ValuesController : Controller
{
const string LogFolder = @"C:\Data\Count";
String[] result = Directory.GetFiles(LogFolder);
// GET api/values
[HttpGet]
public JsonResult Get()//System.Net.Http.HttpResponseMessage Get() //IEnumerable<string>
{
List<string> allFiles = System.IO.Directory.GetFiles(LogFolder).ToList();
allFiles.Reverse(); //newest on top
return Json(allFiles) ;
【问题讨论】:
-
试试
return Content(answer)。 -
无法识别作为动词的内容,命名空间需要什么?
-
ControllerBase.Content 应该可以访问,除非您不使用
Microsoft.AspNetCore.Mvc.Controller? -
我已经添加了它,但它仍然在网络浏览器中输出纯文本(即使是强制的 html 格式也不起作用)(尽管我认为它不应该被强制执行)。
-
将您的返回类型更改为
ActionResult,然后尝试使用Content()。
标签: c# routes .net-core http-get asp.net-core-webapi