【问题标题】:Why does LinkGenerator.GetUriByPage() "values" parameter return string.Length when a string is passed in?为什么LinkGenerator.GetUriByPage()“values”参数在传入字符串时返回string.Length?
【发布时间】:2020-07-21 20:30:13
【问题描述】:

我是 ASP.NET Core 新手,刚刚学习一些新概念...

当我使用生成链接时

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

我正在尝试我只是想了解为什么会这样,documentation 没有太多关于幕后行为的信息。

测试代码

// 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);

【问题讨论】:

标签: c# asp.net-core


【解决方案1】:

values 参数被传递给RouteValueDictionary 类构造函数。该类需要一个键/值集或一个对象,其中属性及其值用于创建字典。这就是为什么你会看到String.Length

您可以传递一个带有您要解析 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);

您可以在232here 行的文档中看到values 参数向RouteValueDictonary 的传递。

【讨论】:

  • 猜我应该有 RTFM...谢谢!
  • 不要对自己太苛刻......任何人在学习时都会忽略一些东西。编码愉快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 2011-11-04
  • 1970-01-01
相关资源
最近更新 更多