运行环境:ASP.NET 4.5.2。

当我们向GlobalConfiguration.Configuration.MessageHandlers添加一个DelegatingHandler派生类后,很容易发生即使命中了Action,但方法参数值为null的问题。

在大多数情况下,我们会在DelegatingHandler派生类里,重写async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)方法。

在方法内,做一些事情,比如说访问日志记录,任意校验,添加Header,修改URL(重写)等工作。

其中最重要需要注意的一点在于request.Content,当我们在方法内访问了request.Content (get)之后,而不对request.Content进行赋值(set)的话,会发生什么呢?

这会导致我们的方法(action)无法获取到客户端Post上来的数据,导致方法参数值为null。

这是为什么呢,这个中原因,我没去深究。

现在附上解决代码:

 public class DefaultHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.RequestUri = new Uri(request.RequestUri.ToString()); MediaTypeHeaderValue contentType = request.Content.Headers.ContentType; if (contentType != null)
{
switch (contentType.MediaType)
{
case "application/x-www-form-urlencoded":
{
NameValueCollection formData = await request.Content.ReadAsFormDataAsync(cancellationToken);
request.Content = new FormUrlEncodedContent(Correct(formData));
//TODO:在这里对formData进行业务处理
}
break;
case "multipart/form-data":
{
NameValueCollection formData = await request.Content.ReadAsFormDataAsync(cancellationToken);
request.Content = new FormUrlEncodedContent(Correct(formData));
//TODO:在这里对formData进行业务处理
}
break;
case "application/json":
{
HttpContentHeaders oldHeaders = request.Content.Headers;
string formData = await request.Content.ReadAsStringAsync();
request.Content = new StringContent(formData);
ReplaceHeaders(request.Content.Headers, oldHeaders);
//TODO:在这里对formData进行业务处理
}
break;
default:
throw new Exception("Implement It!");
}
} return await base.SendAsync(request, cancellationToken);
} private static IEnumerable<KeyValuePair<string, string>> Correct(NameValueCollection formData)
{
return formData.Keys.Cast<string>().Select(key => new KeyValuePair<string, string>(key, formData[key])).ToList();
} private static void ReplaceHeaders(HttpHeaders currentHeaders, HttpHeaders oldHeaders)
{
currentHeaders.Clear();
foreach (var item in oldHeaders)
currentHeaders.Add(item.Key, item.Value);
}
}

在Global.asax添加代码:

 protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new DefaultHandler());
}

模型类:

 public class TestModel
{
[JsonProperty(PropertyName ="I")]
public long Id { get; set; } [JsonProperty(PropertyName = "N")]
public string Name { get; set; } [JsonProperty(PropertyName = "M")]
public decimal Money { get; set; } [JsonProperty(PropertyName = "IE")]
public bool IsEnable { get; set; } [JsonProperty(PropertyName = "CD")]
public DateTime CreateDate { get; set; } [JsonProperty(PropertyName = "UD")]
public DateTime? UpdateDate { get; set; }
}

ApiController:

 public class DefaultController : ApiController
{
[HttpPost]
public TestModel Find(TestModel model)
{
return model;
}
}

Request Body:

{"I":10000,"N":"TestModel","M":21547855.0001,"IE":true,"CD":"2015-12-10 12:12:12","UD":"2016-01-01 01:01:01"}

Fiddler4测试:

测试结果:

解决办法来自:http://stackoverflow.com/questions/27333419/modify-request-content-in-webapi-delegatinghandler

WebAPI接收JSON参数注意事项的更多相关文章

  1. WebApi传递JSON参数

    开发过程中经常进行JSON的传递,在WebApi中传递JSON字串时,会发现服务器端接收到不参数值,看下面代码 服务端: public void Post([FromBody]string value ...

  2. SpringBoot配置Swagger实例(POST接收json参数)

    工程目录结构: 首先,引入jar包,只需要以下两个即可 <dependency> <groupId>io.springfox</groupId> <artif ...

  3. SpringBoot:自定义注解实现后台接收Json参数

    0.需求 在实际的开发过程中,服务间调用一般使用Json传参的模式,SpringBoot项目无法使用@RequestParam接收Json传参 只有@RequestBody支持Json,但是每次为了一 ...

  4. Spring controller 中接收JSON参数失败

    如果方法中的参数都是JSON类型,则在方法参数前面添加  @RequestBody 注解: public Boolean serverPath(@RequestBody ServerPathReq r ...

  5. springmvc接收json注意事项

            在以前使用SpringMvc框架时,在接受json数据时碰到了一些奇怪的问题.这里记录下来,方便以后查阅. 1. data 里写json对象 , 即该json数据没有被单(双)引号包住 ...

  6. webapi 控制器接收POST参数时必须以对象的方式接收

    webapi    控制器接收POST参数时必须以对象的方式接收

  7. spring接收json格式的多个对象参数(变通法)

    两种方法 方法1 如果使用spring mvc同客户端通信,完全使用json数据格式,需要如下定义一个RequestMapping @Controller public class TestContr ...

  8. Servlet端 接收不到4096,8192长度的JSON参数

    Servlet端的日志显示,客户端传过来的JSON参数是空值. 但是在客户端的日志显示,已将JSON参数传送过去. 经调查发现,加减1位后的JSON参数均可以正常传送. 只有8192,4096长度的J ...

  9. [置顶] webapi token、参数签名是如何生成的

    一个问题 在这里我想问大家一句,如果你向一个刚刚接触.net web后端程序开发的同学(别人刚刚也就学了webform的request,response,会提交表单的这种刚接触不久的同学),你怎么去解 ...

随机推荐

  1. 卡片抽奖插件 CardShow

    这个小项目(卡片秀)是一个卡片抽奖特效插件,用开源项目这样的词语让我多少有些羞愧,毕竟作为一个涉世未深的小伙子,用项目的标准衡量还有很大差距.不过该案例采用 jQuery 插件方式编写,提供配置参数并 ...

  2. 【原创分享·微信支付】C# MVC 微信支付之微信模板消息推送

    微信支付之微信模板消息推送                    今天我要跟大家分享的是“模板消息”的推送,这玩意呢,你说用途嘛,那还是真真的牛逼呐.原因在哪?就是因为它是依赖微信生存的呀,所以他能不 ...

  3. inline-block元素间距问题的几种解决方案

    不知道大家有没有碰到过设置了display:inline-block;的几个相邻元素之间有几px间距的问题,这里提供几种简单实用的解决方法,希望能够帮到大家!   方法1. 将<li>标签 ...

  4. zookeeper源码分析之四服务端(单机)处理请求流程

    上文: zookeeper源码分析之一服务端启动过程 中,我们介绍了zookeeper服务器的启动过程,其中单机是ZookeeperServer启动,集群使用QuorumPeer启动,那么这次我们分析 ...

  5. 深入学习jQuery自定义插件

    原文地址:jQuery自定义插件学习 1.定义插件的方法 对象级别的插件扩展,即为jQuery类的实例增加方法, 调用:$(选择器).函数名(参数);      $(‘#id’).myPlugin(o ...

  6. CSS margin详解

    以下的分享是本人最近几天学习了margin知识后,大有启发,感觉以前对margin的了解简直太浅薄.所以写成以下文章,一是供自己整理思路:二是把知识分享出来,避免各位对margin属性的误解.内容可能 ...

  7. sqlServer去除字符串空格

    说起去除字符串首尾空格大家肯定第一个想到trim()函数,不过在sqlserver中是没有这个函数的,却而代之的是ltrim()和rtrim()两个函数.看到名字所有人都 知道做什么用的了,ltrim ...

  8. Kafka:主要参数详解(转)

    原文地址:http://kafka.apache.org/documentation.html ############################# System ############### ...

  9. hbase协处理器编码实例

    Observer协处理器通常在一个特定的事件(诸如Get或Put)之前或之后发生,相当于RDBMS中的触发器.Endpoint协处理器则类似于RDBMS中的存储过程,因为它可以让你在RegionSer ...

  10. 【swift】BlockOperation和GCD实用代码块

    //BlockOperation // // ViewController.swift import UIKit class ViewController: UIViewController { @I ...