繁体   English   中英

HTTP Post请求正文值null c#

[英]HTTP Post request body values null c#

我正在设置一个带有 .NET Core 后端的反应应用程序。 我正在使用带有用户名值和密码值的 fetch 向后端 c# 用户控制器登录方法发送 HTTP 发布请求。 http请求如下:

function login(username, password) {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
    };

    return fetch(`/user/login`, requestOptions)
        .then(handleResponse)
        .then(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('user', JSON.stringify(user));

            return user;
        });
}

我可以在谷歌开发工具中看到请求是从上面的代码发送的,并且包含用户名和密码。 我在第一行的以下代码上放置了一个断点,可以看到用户名和密码没有填充在 c# 登录方法端,因为它们都是空的。

对于HttpContext.Request ,我尝试了 3 种不同的方法。 形成它会引发null错误。 我尝试使用[FromBody]标记解析方法中的参数并获取null 我也尝试使用流阅读器,但它返回一个空字符串。

[HttpPost]
public JsonResult Login([FromBody] string username, [FromBody] string password) // both are null
{
    System.Diagnostics.Debug.WriteLine("The form has " + username.ToString());
   
    // throws null error
    //string bodyValues = HttpContext.Request.Form["username"];
    
    Stream req = Request.Body;
    //req.Position = 0;
    string json = new StreamReader(req).ReadToEndAsync().Result;

    string input = null;
    try
    {
        input = JsonConvert.DeserializeObject<string>(json);
    }

    catch (Exception ex)
    {
        // Try and handle malformed POST body
        return new  JsonResult("false");
    }

    return new JsonResult("true");
}

任何帮助表示赞赏!

修复你的 javascript

function login(username, password) {
    const requestOptions = {
        method: 'POST',
        body: { username : username, password: password }
    };
......

并尝试删除 [FromBody] 因为你不能使用它两次

[HttpPost]
public JsonResult Login( string username, string password)

如果您仍然有一些问题,请尝试创建视图模型

public class PasViewModel
    {
      public string Username { get; set; }
      public string Password { get; set; }
    }

并将 FromBody 添加到动作视图模型

[HttpPost]
public JsonResult Login( [FromBody] PasViewModel viewModel)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM