首页 > 解决方案 > 为什么方法重载会破坏 Azure 函数路由?

问题描述

假设我在 Azure Function 项目中有一个 C# 方法,看起来像这样,并且运行良好:

[FunctionName( nameof( GetContents) )]
public static async Task<IActionResult> GetContents( [HttpTrigger( AuthorizationLevel.Function, "get", Route="/v1/Contents/{id}" )] HttpRequest req, ILogger log, string id ) {
// ...
}

到现在为止还挺好。现在,创建一个根本没有路由的重载,它根本不是一个 Web 服务,并且只打算用作其他服务的帮助器:

public static async Task<ObjectResult> GetContents( ILogger log, string id, bool isAdmin ) {
// ...
}

现在,原来的 Web 服务方法不再正确路由。如果您尝试点击它,您会得到 404。尽管它已经完美运行并且没有任何改变。重载如何设法破坏原始方法的功能?

标签: c#asp.net-web-apiazure-functions

解决方案


Azure Function 宿主尝试使用级联方法解析该方法,从一个显式定义的方法开始,该方法命名为entryPoint内部编译的function.json. 请参阅FunctionEntryPointResolver.cs#L39

如果入口点方法名称可以返回超过 1 个公共方法,Azure 函数解析器将由于不明确而引发异常。请参见FunctionEntryPointResolver#L94

private static T GetNamedMethod<T>(IEnumerable<T> methods, string methodName, StringComparison stringComparison) where T : IMethodReference
{
    var namedMethods = methods
                .Where(m => m.IsPublic && string.Compare(m.Name, methodName, stringComparison) == 0)
                .ToList();

    // If we have single method that matches the provided name, use it.
    if (namedMethods.Count == 1)
    {
        return namedMethods[0];
    }

    // If we have multiple public methods matching the provided name, throw a compilation exception
    if (namedMethods.Count > 1)
    {
        throw CreateCompilationException(DotNetConstants.AmbiguousFunctionEntryPointsCompilationCode,
            $"Ambiguous function entry points. Multiple methods named '{methodName}'.", $"Multiple methods named '{methodName}'. Consider renaming methods.");
    }
}

推荐阅读