asp.net-mvc-4 - 如何访问 Asp Net MVC 4 Web Api 中自定义模型绑定(bind)器中的请求内容?

标签 asp.net-mvc-4 asp.net-web-api custom-model-binder

我一直在思考如何解决我在上一个问题中遇到的问题

Can I get access to the data that the .net web api model binding was not able to handle?

我认为我可以使用自己的自定义模型绑定(bind)器,这样我就可以处理完美的情况,并在收到我不期望的数据时写入日志。

我有以下类和模型绑定(bind)器

 public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class CustomPersonModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var myPerson = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var myPersonName = bindingContext.ValueProvider.GetValue("Name");

        var myId = bindingContext.ValueProvider.GetValue("Id");

        bindingContext.Model = new Person {Id = 2, Name = "dave"};
        return true;
    }
}

public class CustomPersonModelBinderProvider : ModelBinderProvider
{
    private  CustomPersonModelBinder _customPersonModelBinder = new CustomPersonModelBinder();

    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
    {
        if (modelType == typeof (Person))
        {
            return _customPersonModelBinder;
        }
        return null;
    }
}

这是我的 Controller 方法

   public HttpResponseMessage Post([ModelBinder(typeof(CustomPersonModelBinderProvider))]Person person)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

我一直在使用 fiddler 调用它

Post http://localhost:18475/00.00.001/trial/343

{  
        "Id": 31,
        "Name": "Camera Broken"
}

这效果很好,在不使用自定义模型绑定(bind)程序的情况下,我在 post 方法中得到了一个由 json 数据填充的 Person 对象,并且使用自定义模型绑定(bind)程序我总是得到一个人(Id = 2,Name =“dave”) 。

问题是我似乎无法访问自定义模型绑定(bind)器中的 JSon 数据。

bindModel 方法中的 myPerson 和 myPersonName 变量均为 null。但是 myId 变量填充为 343。

有什么想法可以在 BindModel 方法中访问 json 中的数据吗?

最佳答案

试试这个:

actionContext.Request.Content.ReadAsStreamAsync()

关于asp.net-mvc-4 - 如何访问 Asp Net MVC 4 Web Api 中自定义模型绑定(bind)器中的请求内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13078732/

相关文章:

asp.net - 自定义模型绑定(bind)器未针对 ASP.NET Core 2 中的单个属性触发

c# - 为什么在 web api 中返回具有一对多关系的实体会导致错误?

c# - 提交按钮是否在表单提交时将其值传递给操作方法?

c# - 如何在 ASP.NET Web api 中获取客户端请求的 url?

asp.net - Web API 路由 - api/{controller}/{action}/{id} "dysfunctions"api/{controller}/{id}

java - 如何摆脱错误 "Fatal signal 11 (SIGSEGV), code 1, fault addr 0x70"

twitter-bootstrap - MVC 4 Google 字体 - 内联网

c# - 从 Controller MVC ASP 4 中的列表框中获取项目

asp.net - 缺少 Web API Controller 类模板 VS 2010

asp.net-mvc - Asp.net MVC 中的自定义 DateTime 模型绑定(bind)器