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;'。否则读取器将返回一个空字符串,因为服务器已经自己到达了主体的末端。 –