简体   繁体   English

HTTP Post请求正文值null c#

[英]HTTP Post request body values null c#

I'm setting up a react app with a .NET Core backend.我正在设置一个带有 .NET Core 后端的反应应用程序。 I'm sending a HTTP post request using fetch with the username value and password value to the backend c# user controller login method.我正在使用带有用户名值和密码值的 fetch 向后端 c# 用户控制器登录方法发送 HTTP 发布请求。 The http request is below: 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;
        });
}

I can see in google dev tools that the request is being sent from the code above and contains both a username and password.我可以在谷歌开发工具中看到请求是从上面的代码发送的,并且包含用户名和密码。 I placed a breakpoint on the below code on the first line and can see the username and password are not populating on the c# login method side as they are both null.我在第一行的以下代码上放置了一个断点,可以看到用户名和密码没有填充在 c# 登录方法端,因为它们都是空的。

I've tried 3 different ways, for HttpContext.Request .对于HttpContext.Request ,我尝试了 3 种不同的方法。 Form it throws null error.形成它会引发null错误。 I tried to parse the parameters in the method using the [FromBody] tag and get null .我尝试使用[FromBody]标记解析方法中的参数并获取null I also tried using a stream reader but it returns an empty string.我也尝试使用流阅读器,但它返回一个空字符串。

[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");
}

Any help is appreciated!任何帮助表示赞赏!

fix your javascript修复你的 javascript

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

and try to remove [FromBody] since you can not use it twice并尝试删除 [FromBody] 因为你不能使用它两次

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

if you still have some problems try to create view model如果您仍然有一些问题,请尝试创建视图模型

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

and add FromBody to action view model并将 FromBody 添加到动作视图模型

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

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

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