繁体   English   中英

为什么LinkGenerator.GetUriByPage()“values”参数在传入字符串时返回string.Length?

[英]Why does LinkGenerator.GetUriByPage() “values” parameter return string.Length when a string is passed in?

我是 ASP.NET 内核的新手,只是学习一些新概念......

当我使用生成链接时

public static string GetUriByPage (this Microsoft.AspNetCore.Routing.LinkGenerator generator, 
                                    string page, string handler, object values, 
                                    string scheme, Microsoft.AspNetCore.Http.HostString host, 
                                    Microsoft.AspNetCore.Http.PathString pathBase = default, 
                                    Microsoft.AspNetCore.Http.FragmentString fragment = default, 
                                    Microsoft.AspNetCore.Routing.LinkOptions options = default);

values字段将输入作为类型object 如果我尝试插入一个字符串作为 object,它将采用Length字符串属性的值而不是字符串变量的值。 我假设values字段获取 object 的所有公共属性,这就是它的工作原理,但是我如何能够只传递字符串值而不是公共属性?

我试图我只是想了解为什么会这样, 文档没有太多关于幕后行为的信息。

测试代码

// Create a new entry in the hash table
var record = _context.HashRecords.Add(new Data.HashRecord {
    FullName = user.FullName,
    Representative = repName,
    Hash = GetUniqueKey(8)
});

_context.SaveChangesAsync();

string generatedLink = _linkGenerator.GetUriByPage("/Page",
                       handler: null,
                       values: record.Entity,
                       scheme: _httpContextAccessor.HttpContext.Request.Scheme,
                       host: _httpContextAccessor.HttpContext.Request.Host);

values参数被传递给RouteValueDictionary class 构造函数。 class 需要一个键/值集或一个 object 哪些属性及其值用于创建字典。 这就是您看到String.Length的原因。

您可以传递一个匿名 object 和您想要解析 URL 的值。 (更改属性名称以方便您)

// Create a new entry in the hash table
var record = _context.HashRecords.Add(new Data.HashRecord {
    FullName = user.FullName,
    Representative = repName,
    Hash = GetUniqueKey(8)
});

_context.SaveChangesAsync();

string generatedLink = _linkGenerator.GetUriByPage("/Page",
                       handler: null,
                       // Passing an object to be converted to dictionary
                       values: new { entity = record.Entity },
                       scheme: _httpContextAccessor.HttpContext.Request.Scheme,
                       host: _httpContextAccessor.HttpContext.Request.Host);

您可以在此处232行的文档中看到将values参数传递给RouteValueDictonary

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM