【问题标题】:Not getting result of HttpClient.PostAsync()没有得到 HttpClient.PostAsync() 的结果
【发布时间】:2017-11-16 08:50:58
【问题描述】:

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

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的提示,问题解决了一半。检查 1. 是假的。检查2。:Unable to find a constructor to use for type AuthorizationUser. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Headers', line 1, position 11.
    • 所以我添加了一个默认构造函数(添加一个但它是private)。现在,user 不为空,但其中的值为空,ModelState.IsValid 为真。
    • 现在 ModelState.IsValid 为真?
    • 尝试在被调用者的 AuthorizationUser 设置器中设置断点,它们是否命中?
    • 不,他们不打。构造函数是但不是 setter。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多