Skip to content

服务端命Execute函数返回值

ErrCode 和 Message

服务端命令的执行函数 ExecuteAsync 返回值类型为 ExecuteResult 对象

如果执行成功,只需要返回默认的 ExecuteResult对象即可

csharp
public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
{
    return new ExecuteResult();
}

如果需要表示执行失败,应该设置返回的 ExecuteResult 对象的ErrCode属性为一个非 0 值。 同时推荐设置 Message 属性说明失败原因。

csharp
public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
{
    return new ExecuteResult()
    {
        ErrCode = 1,
        Message = "库存不足"
    };
}

除了最常用的ErrCode属性和 Message属性,在特定场景下可能需要设置其他 ExecuteResult 实例上的属性以满足不同的需求

自定义响应(Response)内容

默认情况下,服务端命令执行的最终 ExecuteResult 会被写入到 HTTP 请求的 ResponseBody (响应) 中。如此,可以和前端的调用Http请求命令配合,完成前后端逻辑。

但是,有些情况下,服务端命令需要自己控制请求响应内容,此需求在与第三方系统集成时特别有用。通过设置 AllowWriteResultToResponse 为 False 可以阻止活字格把 ExecuteResult 对象写入HTTP 响应

csharp
using GrapeCity.Forguncy.Commands;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace MyPlugin
{
    public class MyPluginServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            await dataContext.Context.Response.WriteAsync("自定义响应的内容");
            return new ExecuteResult() { AllowWriteResultToResponse = false };
        }
        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}

流程控制

默认情况下,如果命令这些成功,会执命令列表中的下一个服务端命令。通过设置 ProcessControl 属性的值,可以命令列表的执行流程

csharp
public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
{
    return new ExecuteResult()
    {
        ProcessControl = ProcessControl.Return
    };
}

ProcessControl 可用选项如下表

Continue默认值,表示继续执行后续命令
Return立即返回,会跳过所有后续命令列表的执行
BreakLoopAndContinue如果当前命令是循环命令的子命令,跳出当前循环,继续执行循环命令之后的命令,类似于编程语言中的 break
ContinueLoop如果当前命令是循环命令的子命令,跳过此次循环的后续命令,继续执行下次循环,类似于编程语言中的 continue

更新: 2022-12-10 11:05:28
原文: https://www.yuque.com/robert-bh51n/ea8l6c/rmkqlfumzw2piuq0