开发需要调用Json REST Api的.NET Core Web应用程序。
来电者:
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
AuthorizationUser user = new AuthorizationUser { User = "<user>", Application = "<app>" };
var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(new Uri("http://localhost:8081/Roles"), content);
// ...
}
被叫方:
[AllowAnonymous]
[HttpPost]
public HttpResponseMessage Post(AuthorizationUser user)
{
try
{
user = FillRoles(user);
return Request.CreateResponse(HttpStatusCode.OK, user);
}
catch (System.Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
模型(在来电者和被叫者中):
public class AuthorizationUser
{
public AuthorizationUser() // Added thanks to CodeFuller
{ }
public AuthorizationUser(string user, string application)
{
User = user ?? throw new ArgumentNullException(nameof(user));
Application = application ?? throw new ArgumentNullException(nameof(application));
}
public string User { get; set; }
public string Application { get; set; }
public IEnumerable<string> Roles { get; set; }
}
当到达被叫方的断点时,收到的user
始终为空。
我尝试在其前添加[FromBody]
和[FromUri]
,但结果相同。
我做错了什么?
答案 0 :(得分:1)
我无法重现您的问题,使用User
和Application
字段正确填充用户。
似乎在模型绑定期间发生了一些错误。要诊断问题,请检查以下内容:
ActionContext.ModelState.IsValid
方法中Post()
的价值是多少?是true
还是false
?ActionContext.ModelState.Values
。它应该包含模型绑定错误。