尝试访问自定义过滤器

时间:2017-05-22 12:32:54

标签: asp.net asp.net-core

我正在开发asp.net核心Web应用程序。当我尝试访问自定义过滤器中的帖子数据时,如下所示:

public class CustomFilter : Attribute, IAsyncActionFilter
    {

        private ActionExecutingContext _context;

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            _context = context;

            var dict = _context.HttpContext.Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString()); // got error her

            //int id = dict[“id”];
...

我得到了这个例外

  

InvalidOperationException:Incorrect Content-Type:application / json。

我使用XMLHttpRequest将数据发送到服务器。这是配置:

var xhr = new XMLHttpRequest();

xhr.open(“post”, url, true);

xhr.setRequestHeader('Content-Type', 'application/jso

xhr.send(JSON.stringify(dataToSent));

1 个答案:

答案 0 :(得分:0)

如果您发布application/json正文(内置有效JSON),则不能将其视为表单数据(通常为application/x-www-form-urlencoded)。读取原始体并反序列化:

public class CustomFilter : Attribute, IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        var stream = context.HttpContext.Request.Body;

        string json = new StreamReader(stream).ReadToEnd();

        //Foo obj = JsonConvert.DeserializeObject<Foo>();
    }
}