没有得到HttpClient.PostAsync()的结果

时间:2017-11-16 08:50:59

标签: c# asp.net-web-api dotnet-httpclient

开发需要调用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],但结果相同。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我无法重现您的问题,使用UserApplication字段正确填充用户。

似乎在模型绑定期间发生了一些错误。要诊断问题,请检查以下内容:

  1. ActionContext.ModelState.IsValid方法中Post()的价值是多少?是true还是false
  2. 如果为false,请在调试器中检查集合ActionContext.ModelState.Values。它应该包含模型绑定错误。