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

问题描述:

我试图为此找到一种解决方案,但是所有即将发布的解决方案都是针对ASP.Net的早期版本的.

I've tried to find a solution for this, but all the ones coming up are for previous versions of ASP.Net.

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

I'm working with the JWT authentication middleware and have the following method:

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发送.

This gets the sent data as if it was form data, but my Angular 2 front end is sending the data as 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并仅发送表单数据,它就可以正常工作.

My preferred solution is to send it as JSON, but I've been unsuccessful in retrieving the data. I know it's sending, because I can see it in fiddler, and if I use Postman and just send form data it works fine.

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

Basically I just need to figure out how to change this line to read the json data

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

到中间件时,请求流已经被读取,因此您可以在 Microsoft.AspNetCore.Http.Internal上进行操作. .在请求上启用快退,然后自己阅读

By the time it gets to your middleware the request stream has already been read, so what you can do here is Microsoft.AspNetCore.Http.Internal.EnableRewind on the Request and read it yourself

站点范围:

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();
    ...
    }