我有这个端点方法:
var authToken = await [url]
.AddAuthHeaders(config)
.PostJsonAsync(new AuthTokenRequest
{
GrantType = "test",
ClientId = "test",
ClientSecret = "test",
Audience = "test"
})
.ReceiveJson<AuthTokenResponse>();
它调用这个端点:
[HttpPost]
public IActionResult Get([FromBody] object request)
{
try
{
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "test")
}),
Issuer = _issuer,
Audience = _audience,
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_key)),
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
// Create a new instance of the AuthTokenResponse class and set its properties
var response = new AuthTokenResponse
{
AccessToken = tokenHandler.WriteToken(token).ToString(),
TokenType = "Bearer",
ExpiresSeconds = token.ValidTo.Subtract(token.ValidFrom).TotalSeconds.ToString(),
AuthTokenType = AuthTokenType.Generic
};
return Ok(response);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating token for request {Request}", request);
return BadRequest();
}
}
我的AuthTokenReponse
类是:
[DataContract]
public class AuthTokenResponse
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
[DataMember(Name = "expires_in")]
public string ExpiresSeconds { get; set; }
public AuthTokenType AuthTokenType { get; set; }
}
public enum AuthTokenType
{
Generic,
Custom
}
现在,当我使用post方法调用端点时,它会按预期到达终点,并且我可以看到响应对象生成了所有正确的属性。它生成一个令牌,我可以清楚地看到,并返回一个有效的响应对象。
然而,接收对象的应用程序接收到:
AccessToken null
TokenType null
ExpiresSeconds null
AuthTokenType Generic
除了AuthTokenType
有正确的值外,其他都是null。
当我使用postman我得到正确的值
{
"accessToken": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Indob2NhcmVzaXRzZmFrZSIsIm5iZiI6MTY4MzMxNDAxMiwiZXhwIjoxNjgzMzE3NjEyLCJpYXQiOjE2ODMzMTQwMTIsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjUwODg5LyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjUwODg5LyJ9.W_qvEBeF4gGMYAKA6n09bYPWsKrWvpEwRc0b7DdZuNJf4RDU25yh3GUv5Ht0UupoBqGYHDBfBjR8O21sv-56rg",
"tokenType": "Bearer",
"expiresSeconds": "3600",
"authTokenType": 0
}
我不明白为什么会这样?是因为对象没有序列化它的属性吗?有什么想法吗
2条答案
按热度按时间z9smfwbn1#
问题似乎出在数据合约属性上。假设你使用的是默认的Flurl序列化器-- Newtonsoft的Json.NET,它将荣誉属性(see the docs)。删除
DataMember
属性或添加JsonProperty
属性(将优先):3duebb1j2#
问题似乎是
ReceiveJson需要一个json序列化对象,
我通过在发送之前序列化对象来修复这个问题