2017-10-31 4 views
0

C#アプリケーションから呼び出すときに正常に動作しているREST呼び出しがありますが、JavaScriptページから本文に内容を送信することはできませんPOSTのこれがRESTコントローラです。コールから「FromBody」属性を削除すると、以下のJavaScriptが正常に動作することに注意してください。ASP.NET REST POST - JavaScript(jQuery)POSTで本文を送信する

[Route("api/[controller]")] 
public class AuthenticateController : Controller 
{ 
    [HttpPost] 
    public ActionResult Post([FromBody] CredentialsModel credentialsModel) 
    { 
     var authenticationModel = new AuthenticationModel { IsSuccess = false }; 

     if (credentialsModel != null && !string.IsNullOrEmpty(credentialsModel.Username) && !string.IsNullOrEmpty(credentialsModel.Password)) 
     { 
      authenticationModel = SecurityBusinessLayer.IsValidUser(credentialsModel.Username, credentialsModel.Password); 
     } 

     var json = JsonConvert.SerializeObject(authenticationModel, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Serialize }); 

     return Content(json); 
    } 
} 

これはjQueryのを使用したJavaScriptです:

function authenticate(username, password) 
{ 
    //Get the authenticate api url 
    var uriHref = window.location.href; 
    var lastIndexOfSlash = uriHref.lastIndexOf('/'); 
    var apiPath = uriHref.substring(0, lastIndexOfSlash) + "/api"; 
    var encodedUri = encodeURI(apiPath + "/authenticate/"); 

    var credentials = {}; 
    credentials["Username"] = username; 
    credentials["Password"] = password; 

    //Post the username and password to the server 
    $.post(encodedUri, credentials, function (data) 
    { 
     //Parse the returned data (should match Adapt.Data.Generic.AuthenticationModel) 
     var response = JSON.parse(data); 

     if (response.IsSuccess) 
     { 
      //Ensure the token will expire 
      var expiryDate = new Date(); 
      expiryDate = new Date(expiryDate.setTime(expiryDate.getTime() + 86400000)); 

      //Set the auth token cookie 
      var cookieString = "authToken=" + response.Authtoken + "; expires=" + expiryDate.toUTCString() + ";path=/"; 
      document.cookie = cookieString; 

      //Goto the xivic app page 
      window.location = "Index.html"; 
     } 
     else 
     { 
      //Failed to log in, show error message 
      $("#badLoginMessage").css("visibility", "visible"); 
     } 
    }); 
} 
+0

'credentials'オブジェクトを文字列にする必要があります。' JSON.stringify(credentials) ' – ibubi

+0

私はそれを試しました。私はもう一度やり直します。 –

+0

@ibubi私はあなたの提案を試みたが、それは違いはなかった。 –

答えて

1

@LeTungAnhと@ ibubiのコードに基づいた作業コードです。私は助けることができないが、$ポストはまだ良い方法だと思う。 $ postがうまくいかなかった理由は、ASP.NET Coreが要求するapplication/jsonのコンテンツタイプを送信していないということでした。

function authenticate(username, password) { 
    //Get the authenticate api url 
    var uriHref = window.location.href; 
    var lastIndexOfSlash = uriHref.lastIndexOf('/'); 
    var apiPath = uriHref.substring(0, lastIndexOfSlash) + "/api"; 
    var encodedUri = encodeURI(apiPath + "/authenticate/"); 

    var credentials = {}; 
    credentials["Username"] = username; 
    credentials["Password"] = password; 

    var credentialsJson = JSON.stringify(credentials); 

    $.ajax({ 
     url: encodedUri, 
     type: 'POST', 
     data: credentialsJson, 
     contentType: 'application/json', 
     success: function (responseJson) { 

      var authenticationObject = JSON.parse(responseJson) 

      if (authenticationObject.IsSuccess == true) { 

       //Ensure the token will expire 
       var expiryDate = new Date(); 
       expiryDate = new Date(expiryDate.setTime(expiryDate.getTime() + 86400000)); 

       //Set the auth token cookie 
       var cookieString = "authToken=" + authenticationObject.Authtoken + "; expires=" + expiryDate.toUTCString() + ";path=/"; 
       document.cookie = cookieString; 

       //Goto the xivic app page 
       window.location = "Index.html"; 
      } 
      else { 
       //Failed to log in, show error message 
       $("#badLoginMessage").css("visibility", "visible"); 
      } 

     }, 
     error: function() { 
      //Failed to log in, show error message 
      $("#badLoginMessage").css("visibility", "visible"); 
     }, 
     complete: function() { 
     } 
    }); 
} 
1

削除すると、[FromBodyを、あなたの代わりに、配列のJSONオブジェクトを掲示しなければならない]

$.ajax({ 
 
       url: encodedUri, 
 
       type: 'POST', 
 
       data: { 
 
        Username: jsonString,Password:password 
 
       }, 
 
       success: function (data) { 
 
        if (data.Success == true) { 
 
         
 
        } 
 
        else 
 
        { 
 
         
 
        } 
 

 
       }, 
 
       error: function() { 
 

 
       }, 
 
       complete: function() { 
 
       } 
 
      });

+0

私はFromBodyを削除しませんでした。それは私のサンプルの中にあります。 –

関連する問題