8

我試圖找到一個解決方案,但所有的問題都是針對以前版本的ASP.Net。在ASP.Net中讀取JSON發佈數據核心MVC

我與智威湯遜認證中間件工作,有以下方法:

private async Task GenerateToken(HttpContext context) 
{ 
    var username = context.Request.Form["username"]; 
    var password = context.Request.Form["password"]; 
    //Remainder of login code 
} 

這得到發送的數據,如果它是形式的數據,但我的角2前端發送數據作爲JSON 。

login(username: string, password: string): Observable<boolean> { 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    let body = JSON.stringify({ username: username, password: password }); 
        return this.http.post(this._api.apiUrl + 'token', body, options) 
            .map((response: Response) => { 
                 
            }); 
    } 

我首選的方案是將其作爲發送JSON,但我已經在檢索數據是不成功的。我知道它正在發送,因爲我可以在提琴手中看到它,如果我使用Postman併發送表單數據,它可以正常工作。

基本上,我只需要弄清楚如何改變這一行來讀取JSON數據

var username = context.Request.Form["username"]; 
+0

你爲什麼不只是切換您登錄功能使用的Content-Type'應用程序/ x-WWW的形式urlencoded',只是URL編碼的JSON –

+0

我想整個前端能夠發送json而不是有一些使用json和一些使用表單數據。儘管我確實嘗試了這條路線,但卻很難將數據作爲表單數據正確發送。即使有例子,我也無法讓這兩個人正確對話。 – Jhorra

+0

你不應該只能這樣做嗎? 'encodeURIComponent(JSON.stringify({username:username,password:password}));' –

回答

7

通過請求流已經閱讀它得到您的中間件的時候,所以你可以在這裏做是對請求Microsoft.AspNetCore.Http.Internal.EnableRewind和自己

網站廣泛閱讀:

Startup.cs 
using Microsoft.AspNetCore.Http.Internal; 

Startup.Configure(...){ 
... 
//Its important the rewind us added before UseMvc 
app.Use(next => context => { context.Request.EnableRewind(); return next(context); }); 
app.UseMvc() 
... 
} 

或選擇性:

private async Task GenerateToken(HttpContext context) 
    { 
    context.Request.EnableRewind(); 
    string jsonData = new StreamReader(context.Request.Body).ReadToEnd(); 
    ... 
    } 
+0

你爲什麼在中間件和GenerateToken方法中調用EnableRewind? –

+0

好點@JimAho - 編輯。 –

+1

第二個選項必須在這兩行之間添加'context.Request.Body.Position = 0;'。否則讀取器將返回一個空字符串,因爲服務器已經自己到達了主體的末端。 –