2

使用ServiceStack 的 Razor Story,我们有多种方法来选择我们想要使用哪个 Razor 视图来呈现页面。更好,对我来说至关重要的是,我们还可以传入 Content-Type 标头(或查询字符串参数,甚至是页面“后缀”)以返回各种格式的原始模型。

有没有办法使用ServiceStack 模板(现在称为SharpScript)来做同样的事情?我按照这里的例子,但我只是得到标准的 HTML 格式响应。它不使用我的模板,无论如何命名。

按照v5.5 发行说明中的​​示例:

[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
    public string Name { get; set; }
}
public class HelloResponse
{
    public string Result { get; set; }
}

public class HelloService : Service
{
    public object Any(Hello request) => new HelloResponse { Result = $"Hello, {request.Name}!" };
}

Going to/hello/World?format=html为我提供标准的 HTML 报告,而不是我的模板。我按照另一个示例强制它使用模板....

public object Any(Hello request) =>
        new PageResult(Request.GetPage("examples/hello")) {
            Model = request.Name
        };

...并且它总是返回我的模板,即使我指定/hello/World?format=json.

有什么方法可以为 ServiceStack + ScriptSharp 页面提供类似 Razor 的视图选择,而且还支持不同的响应格式?

4

2 回答 2

2

如果没有您想要实现的特定场景的详细信息,那么很难回答这样一个模糊的问题,但这是行不通的。

您可以通过多种方式返回Sharp Pages :

  • 当它被直接作为内容页面请求时,例如/dir/page->/dir/page.html
  • 使用基于页面的路由,例如/dir/1->/dir/_id.html
  • 当服务以Request DTOResponse DTO命名时,作为响应服务的视图页面,例如->或/contacts/1/Views/GetContact.html/Views/GetContactResponse.html

通过在 custom 中返回 Response DTO 来选择要在 Service 中呈现的视图HttpResult

public object Any(MyRequest request)
{
    ...
    return new HttpResult(response)
    {
        View = "CustomPage",  // -> /Views/CustomPage.html
        //Template = "_custom-layout",
    };
}

添加[ClientCanSwapTemplates]Request Filter 属性以让 View 和 Template 通过在 QueryString 上进行修改,例如:?View=CustomPage&Template=_custom-layout

[ClientCanSwapTemplates]
public object Any(MyRequest request) => ...

通过返回自定义选择要在模型视图控制器服务PageResult中呈现的页面:

public class CustomerServices : Service
{
    public object Any(ViewCustomer request) =>
        new PageResult(Request.GetPage("examples/customer")) {
            Model = TemplateQueryData.GetCustomer(request.Id)
        };
}

注意:SharpPagesFeature使用您的级联解析页面AppHost.VirtualFileSources。在 .NET Core 中,它被配置为使用其WebRoot,例如/wwwroot.

对于 Sharp Pages 以多种内容类型返回其响应:

以及以各种格式返回原始模型。

您需要使用具有值的Sharp APIreturn例如/hello/_name/index.html

{{ { result: `Hello, ${name}!` } | return }}
于 2019-03-27T21:24:36.313 回答
1

为了简洁地回答我自己的问题,@mythz 的第一个选项是我需要的。调用Plugins.Add(new SharpPagesFeature())my后AppHost,我需要HttpResult从我的服务方法返回:

public object Any(MyRequest request)
{
    ...
    return new HttpResult(response)
    {
        View = "CustomPage",  // -> /Views/CustomPage.html
        //Template = "_custom-layout",
    };
}
于 2019-03-28T13:33:03.103 回答