簡體   English   中英

從Node.js將數據發布到ASP.NET WEB API服務

[英]POSTing data to ASP.NET WEB API Service from Node.js

我目前正在開發一個應用程序,以允許公司的高管從任何地方執行某些操作。 我的Node.js部分充當Internet與公司內部LAN之間的代理,並在公司LAN上調用一些ASP.NET WEB API服務來處理Active Directory身份驗證(以便執行人員可以使用其Windows登錄)以及存儲和檢索數據。從SQL Server 2008。

ASP.Net AuthenticateUser()函數接受包含userId和pas的HTTP POST請求,並返回包含客戶端可用來對請求進行簽名的哈希的JSON對象。 當我將userId和密碼作為查詢參數傳遞時,它可以正常工作,但是當我嘗試將它們嵌入到請求正文中時,它會失敗。 工作版本如下所示。 注:我省略了錯誤處理以提高清晰度。)

    namespace Approver.Controllers 
   {
      public class UtilityController : ApiController 
      {
        public UserInfo AuthenticateUser(string userId, string password) 
        {
          return UtilityBo.AuthenticateUser(userId, password); 
        } 
      } 
   }

有效的Node.js代碼(即Express中的路由)如下所示。

exports.login = function(req, res){
var userId = req.body.userId;
var password = req.body.password;
var postData = 'userId='+userId+'&password='+password;
});
var options = {
  host: res.app.settings['serviceHost'],
  port: res.app.settings['servicePort'],
  path: '/api/Utility/AuthenticateUser?userId='+userId+'&password='+password,
  method: 'POST',
  header: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};      
http.request(options, function(resp){
  resp.setEncoding('utf8');
  var arr = '';
  resp.on('data', function (chunk){
    arr += chunk;
  });
  resp.on('end', function (){
    var data = JSON.parse(arr);
    res.writeHead(200, {'Content-Type': 'application/json',});
    res.end(JSON.stringify(data));
  });
}).end(JSON.stringify(postData));

當我更改代碼以僅接受來自正文的數據時,IIS返回HTTP 500錯誤。 新的WEB API服務如下所示。

namespace Approver.Controllers 
{
  public class UtilityController : ApiController 
 {
    public UserInfo AuthenticateUser(UserAuthentication userAuth) 
    {
      return UtilityBo.AuthenticateUser(userAuth); 
    } 
  } 
}

namespace Approver.Models 
{
  public class UserAuthentication 
  {
    [Required] 
    public string UserId { get; set; }

    [Required] 
    public string Password { get; set; } 
  } 
}

新的Node代碼只是從URL中剝離查詢參數。

經過一些測試后,我意識到Web api從未將數據插入模型中,因此userAuth始終具有空值。 但是,我嘗試通過Chrome的REST控制台發布數據,並且該數據有效,因此Node.js片段必須包含錯誤。 我該如何解決?

我認為您在Uri遇到的“模型綁定”問題。

嘗試顯式指定FromUri屬性。

namespace Approver.Controllers 
{
  public class UtilityController : ApiController 
 {
    public UserInfo AuthenticateUser([FromUri] UserAuthentication userAuth) 
    {
      return UtilityBo.AuthenticateUser(userAuth); 
    } 
  } 
}

如果要同時從body和uri綁定參數,請嘗試使用

namespace Approver.Controllers 
{
  public class UtilityController : ApiController 
 {
    public UserInfo AuthenticateUser([ModelBinder] UserAuthentication userAuth) 
    {
      return UtilityBo.AuthenticateUser(userAuth); 
    } 
  } 
}

本文很好地了解了ASP.NET Web API中的模型綁定

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM