簡體   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