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
}
这会将发送的数据视为表单数据,但我的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) => {
                
            });
    }
我首选的解决方案是将其作为JSON发送,但我在检索数据时失败了.我知道它正在发送,因为我可以在小提琴手中看到它,如果我使用Postman并且只是发送表单数据就可以了.
基本上我只需要弄清楚如何更改此行以读取json数据
var username = context.Request.Form["username"];
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()
...
}
或选择性:
private async Task GenerateToken(HttpContext context)
    {
     context.Request.EnableRewind();
     string jsonData = new StreamReader(context.Request.Body).ReadToEnd();
    ...
    }
| 归档时间: | 
 | 
| 查看次数: | 7566 次 | 
| 最近记录: |