【问题标题】:.net core web api returns only clear text, should be based on client capabilities.net core web api 只返回明文,应该基于客户端能力
【发布时间】: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


【解决方案1】:

在 .net core ASP MCV 2.0.x 中,无法单击从 [HTTPGET] 检索到的 Json 列表。由于 .net core 1.0 中存在跨站脚本漏洞

虽然可以使用路由解决它,并为 Web 结果创建特定路由,并为 Web API 提供不同的路由。

有一个网站http://x.x.x.x/Api/valeus
=> 用于 Json 与 GET/PUT 交互

有一个网站http://x.x.x.x/Web/Welcome
=> 对于网络结果,.interact 与 Views MVC(剃须刀页面)。

其他路线也是可能的,具体取决于您的路线过滤器 路由可以基于客户端功能,.. 我认为但这在很大程度上取决于客户端浏览器,创建基于清晰路径的路由可能需要更多的工作,但要保持清晰。

PS 开箱即用的模板可能更容易使用。 但是如果你不能使用它(就像我的例子)那么我希望上面是有用的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多