c# - 按类型或字符串类型强类型 Azure 移动服务表对象?

标签 c# azure reflection azure-mobile-services strong-typing

我想为一些应用程序使用单一的移动服务。我希望它们每个人都使用相同的类(即“Log”),但我希望服务器后端上的信息转到单独的表。我是从可移植类库中执行此操作的。

一种选择是使用 [DataTable(string)] 属性;但是,我希望整个事情能够自动化(即项目中包含单个 DLL,该 DLL 将自动从上下文(即字符串 +“Log”)构造表名称)。我找不到修改 DataTable 属性运行时以获取对强类型表的引用的方法。

除了使用弱类型表并自己序列化 JSON 之外,我还有其他选择吗?或者是否可以仅根据类型或类型名称创建强类型引用?

最佳答案

无法根据运行时中的某些信息更改数据表的名称(此功能存在于 Android SDK 中,因此您可以考虑 creating a feature request 将其也添加到托管 SDK 中)。

但是,您可以使用消息处理程序来“调整”表相关操作的请求 URI,以便您可以通过编程方式实现此目的。基本上,除了您希望在多个应用程序之间共享的数据类型之外,您的可移植库还会公开一个从 DelegatingHandler 扩展的类,该类可以执行此操作。下面是此类处理程序的示例。

public class AppSpecificTableNamesHandler : DelegatingHandler
{
    public const string TablePrefix = "MyType";
    private const string TablesPathPrefix = "/tables/";

    private string tableSuffix;
    public AppSpecificTableNamesHandler(string tableSuffix)
    {
        this.tableSuffix = tableSuffix;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        UriBuilder uriBuilder = new UriBuilder(request.RequestUri);
        string path = uriBuilder.Path;
        if (path.StartsWith(TablesPathPrefix + TablePrefix))
        {
            path = TablesPathPrefix + TablePrefix +
                this.tableSuffix + path.Substring(TablesPathPrefix.Length + TablePrefix.Length);
            uriBuilder.Path = path;
            request.RequestUri = uriBuilder.Uri;
        }

        return base.SendAsync(request, cancellationToken);
    }
}

您可以在 https://gist.github.com/carlosfigueira/9582c08851d116f5a426 找到我用来测试该解决方案(至少是最重要的类)的完整代码。 .

关于c# - 按类型或字符串类型强类型 Azure 移动服务表对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25246280/

相关文章:

java - 在方法调用期间将数组作为参数传递时出现 IllegalArgumentException

c# - 如何检查字符串是否不等于多个字符串

.net - 在本地运行 Azure 模拟器以进行生产

Azure - 创建 bool 变量并在多个任务中使用它

azure - 重新启动 Azure 容器实例

c# - 如何将方法注入(inject) .Net Framework 中的自动属性

c# - 在 Html.DropDownList 中显示 XML 文件内容

c# - 在 C# ASP.NET 中添加自定义 hashAlgorithmType

c# - 如何使用 System.Drawing 将旋转的字符串绘制为图像?

c# - 如何有效地测试 Action 是否装饰有属性(AuthorizeAttribute)?