【发布时间】:2015-10-19 04:00:57
【问题描述】:
我正在尝试在 ASP.net 5 中访问请求的原始输入正文/流。过去,我能够将输入流的位置重置为 0 并将其读入内存流,但是当我尝试要从上下文中执行此操作,输入流要么为空,要么引发错误(System.NotSupportedException =>“不支持指定的方法。”)。
在下面的第一个示例中,如果我将控制器方法的参数对象类型声明为动态,我可以访问控制器中的原始请求。由于各种原因,这不是一个解决方案,无论如何我都需要访问身份验证过滤器中的原始请求正文。
这个例子有效,但不是一个合理的解决方案:
[HttpPost("requestme")]
public string GetRequestBody([FromBody] dynamic body)
{
return body.ToString();
}
抛出错误:
[HttpPost("requestme")]
public string GetRequestBody()
{
var m = new MemoryStream();
Request.Body.CopyTo(m);
var contentLength = m.Length;
var b = System.Text.Encoding.UTF8.GetString(m.ToArray());
return b;
}
抛出错误:
[HttpPost("requestme")]
public string GetRequestBody()
{
Request.Body.Position = 0;
var input = new StreamReader(Request.Body).ReadToEnd();
return input;
}
抛出错误:
[HttpPost("requestme")]
public string GetRequestBody()
{
Request.Body.Position = 0;
var input = new MemoryStream();
Request.Body.CopyTo(input);
var inputString = System.Text.Encoding.UTF8.GetString(input.ToArray());
return inputString;
}
我需要访问我正在构建的 API 的每个请求的原始请求正文。
任何帮助或指导将不胜感激!
编辑:
这是我要读取请求正文的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Http;
namespace API.Filters
{
public class CustomAuthorizationAttribute : Attribute, IAuthorizationFilter
{
public CustomAuthorizationAttribute()
{ }
public void OnAuthorization(AuthorizationContext context)
{
if (context == null)
throw new ArgumentNullException("OnAuthorization AuthorizationContext context can not be null.");
else
{
if (this.AuthorizeCore(context.HttpContext) == false)
{
// Do Other Stuff To Check Auth
}
else
{
context.Result = new HttpUnauthorizedResult();
}
}
}
protected virtual bool AuthorizeCore(HttpContext httpContext)
{
var result = false;
using (System.IO.MemoryStream m = new System.IO.MemoryStream())
{
try
{
if (httpContext.Request.Body.CanSeek == true)
httpContext.Request.Body.Position = 0;
httpContext.Request.Body.CopyTo(m);
var bodyString = System.Text.Encoding.UTF8.GetString(m.ToArray());
return CheckBody(bodyString); // Initial Auth Check returns true/false <-- Not Shown In Code Here on Stack Overflow
}
catch (Exception ex)
{
Logger.WriteLine(ex.Message);
}
}
return false;
}
}
}
当调用标记有 CustomAuthorization 属性的控制器方法时,将访问此代码。
[Filters.CustomAuthorizationAuthorization]
[HttpPost]
public ActionResult Post([FromBody]UserModel Profile)
{
// Process Profile
}
【问题讨论】:
-
抛出的错误是什么?
-
无论如何我都需要在身份验证过滤器中访问原始请求正文 ...这个问答可能会有所帮助stackoverflow.com/q/31464359/571637
-
@haim770 错误是我帖子的顶部,它的 System.NotSupportedException 消息->“不支持指定的方法。”
标签: asp.net-core asp.net-core-mvc asp.net-core-webapi