【问题标题】:AspnetCore RazorPage return raw string?AspnetCore RazorPage 返回原始字符串?
【发布时间】:2023-04-05 09:01:01
【问题描述】:

RazorPage通常返回void、Task、IActionResult等

public Task OnGet() { }
public Task<IActionResult> OnGet() { }

也有可能有一个处理程序返回 Json,比如

public Task<JsonResult> OnGetAlso() { }

但在某些情况下,我希望处理程序返回原始字符串,但我找不到简单的方法来做到这一点。

public Task<string> OnGetSomeString() 
{ return "something"; }

但我总是收到错误不支持的处理程序方法返回类型。这可能吗?谢谢

【问题讨论】:

    标签: asp.net-core razor-pages


    【解决方案1】:

    您需要包含TextOutputFormatter:

    services.AddMvc(options =>
    {
        options.OutputFormatters.Add(new TextOutputFormatter());
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    

    但是,实际上应该默认包含它,这有点奇怪。尽管如此,为了返回一个字符串,你需要TextOutputFormatter,所以如果返回一个字符串不起作用,那么它一定不存在。也许您明确删除了它?

    【讨论】:

    • TextOutputFormatter 构造函数受保护。我试过 options.OutputFormatters.Add(new StringOutputFormatter());但仍然得到“不支持的处理程序方法返回类型'System.String'。这是一个标准的剃须刀页面项目。
    【解决方案2】:

    @Chris Pratt 感谢您的帮助。这似乎有效

        public IActionResult OnGetTest()
        {
            return new ObjectResult("test");
        }
    

    【讨论】:

      【解决方案3】:

      使用ContentResult 返回string 内容:

      public IActionResult OnGetSomeString()
      {
          return Content("something");
      }
      

      【讨论】:

      • 谢谢,这样更优雅。
      • 谢谢,请务必查看所有其他 overloadsContent 方法以及整个 PageModel 类的所有属性/方法!
      猜你喜欢
      • 2013-11-29
      • 2020-02-08
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2012-12-12
      • 2020-06-29
      • 1970-01-01
      相关资源
      最近更新 更多