在ASP.Net Core MVC中读取JSON post数据

我试图找到一个解决方案,但所有出现的都是以前版本的ASP.Net。

我正在使用JWT身份validation中间件并具有以下方法:

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

这会将发送的数据视为表单数据,但我的Angular 2前端将数据作为JSON发送。

 login(username: string, password: string): Observable { 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"]; 

当它到达你的中间件时,请求流已被读取,所以你可以在这里做的是请求上的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(); ... }