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

Jho*_*rra 11 c# asp.net json asp.net-core-middleware asp.net-core-webapi

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

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

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

这会将发送的数据视为表单数据,但我的Angular 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) => {
                
            });
    }
Run Code Online (Sandbox Code Playgroud)

我首选的解决方案是将其作为JSON发送,但我在检索数据时失败了.我知道它正在发送,因为我可以在小提琴手中看到它,如果我使用Postman并且只是发送表单数据就可以了.

基本上我只需要弄清楚如何更改此行以读取json数据

var username = context.Request.Form["username"];
Run Code Online (Sandbox Code Playgroud)

Nat*_*tta 10

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

或选择性:

private async Task GenerateToken(HttpContext context)
    {
     context.Request.EnableRewind();
     string jsonData = new StreamReader(context.Request.Body).ReadToEnd();
    ...
    }
Run Code Online (Sandbox Code Playgroud)

  • 使用第二个选项,您必须在这两行之间添加`context.Request.Body.Position = 0;`.否则,阅读器返回一个空字符串,因为服务器已经自己到达了主体的末尾. (2认同)
  • 在.Net Core 2中,我不得不添加`context.Request.Body.Position = 0;`**之后的'StreamReader`,否则我的帖子会变空. (2认同)