MVC asp.net核心向webapi服务调用传递空值

时间:2016-12-26 05:19:29

标签: c# asp.net asp.net-mvc asp.net-web-api

请求数据

enter image description here

json数据

enter image description here

我不知道,为什么它将空值传递给api?

更新1

这是我的webui操作代码

 const string URLPREFIX = "api/account";
    [HttpPost]
            public async Task<IActionResult> Login(LoginModel loginModel)
            {
                var loginFlag = false;
                HttpResponseMessage response1 = await ServiceCall<LoginModel>.postData(URLPREFIX + "/authenticate",loginModel);
                if (response1.IsSuccessStatusCode)
                {
                    loginFlag = await response1.Content.ReadAsAsync<bool>();
                }

                if (loginFlag)
                {
                    return RedirectToAction("Index","Home");
                }
                else
                {
                    return View();
                }

            }

更新2

public class LoginModel
    {
        [Required]
        [Display(Name = "Username")]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }

任何尝试和回复,谢谢

2 个答案:

答案 0 :(得分:1)

如果您使用Json作为控制器的参数,请在Web API中使用[formbody]。它应该工作。如果它不起作用,请告诉我。

答案 1 :(得分:0)

您必须在控制器级别添加 [ApiController]。代码如下

[ApiController]
[Route("[controller]")]
public class LoginController : ControllerBase 
{
    const string URLPREFIX = "api/account";
    
    [HttpPost]
    public async Task<IActionResult> Login(LoginModel loginModel)
    {
        var loginFlag = false;
        HttpResponseMessage response1 = await ServiceCall<LoginModel>.postData(URLPREFIX + "/authenticate",loginModel);
        if (response1.IsSuccessStatusCode)
        {
            loginFlag = await response1.Content.ReadAsAsync<bool>();
        }

        if (loginFlag)
        {
            return RedirectToAction("Index","Home");
        }
        else
        {
            return View();
        }
    }
}