Reading JSON data in ASP.Net Core MVC

I tried to find a solution for this, but all that works for previous versions of ASP.Net.

I work with 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 } 

Gets the submitted data as if it were form data, but my Angular 2 frontend sends 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) => {                           });    } 

My preferred solution is to send it as JSON, but I could not get the data. I know that it is being sent because I see it as a violinist, and if I use Postman and just submit the form data, it works fine.

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

 var username = context.Request.Form["username"]; 
+8
json c # asp.net-core-webapi asp.net-core-middleware
source share
1 answer

By the time it gets into your middleware, the request stream has already been read, so here you can specify Microsoft.AspNetCore.Http.Internal.EnableRewind in the request and read it yourself

Wide site coverage:

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

OR custom:

 private async Task GenerateToken(HttpContext context) { context.Request.EnableRewind(); string jsonData = new StreamReader(context.Request.Body).ReadToEnd(); ... } 
+7
source share

All Articles