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

编程入门 行业动态 更新时间:2024-10-24 04:51:48
本文介绍了在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(); ... }

更多推荐

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

本文发布于:2023-11-15 17:00:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596303.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Net   ASP   Core   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!