【问题标题】:MVC4 Web API simple parameter types are nullMVC4 Web API 简单参数类型为空
【发布时间】:2014-09-10 13:13:57
【问题描述】:

我正在编写一个使用 MVC 4 Web API 的服务来接收来自第三方服务的POST。这是一个简单的帖子,正文中有一个字符串参数,看起来像key=value

这几乎是 Visual Studio 创建的默认控制器:

// POST api/register
public void Post([FromBody]string value)
{
}

如果我在正文中将参数发布为key=value,则该参数在访问服务时始终为NULL

POST http://localhost:1750/api/Register HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
Host: localhost:1750
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

value=abcdefg

如果我删除密钥并且只发布=value,那么价值就会出现。

POST http://localhost:1750/api/Register HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
Host: localhost:1750
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

=abcdefg

问题是第 3 方服务正在发布 key=value。我怎样才能让我的服务正常工作?

【问题讨论】:

  • 重命名参数为public void Post([FromBody]string key)?
  • 这是我尝试的第一件事。我给参数取什么名字并不重要。
  • 我相信你已经看过你从哪里得到你的解决方法的帖子,但是对于其他人来说,stackoverflow.com/questions/11515319/… 也包含一些有用的链接......
  • 我创建了一个通用的 http 处理程序,它可能更适合我的场景。我将在其他时间尝试查看以下答案。

标签: c# asp.net-mvc-4


【解决方案1】:

你的默认媒体类型是什么?

1 个解决方案

创建一个类

 public Class Item {

     public string Value { get; set;}

    }

然后

[HttpPost]
public void Post([FromBody]Item item)
{ 
  // item.Value should have your data.
}

第二个解决方案 如果您无法控制数据的发送方式,您可以要求他们在发送时对文本进行编码吗?

您可以在其中接收字符串值%3dxyz 然后你可以接收你的字符串变量并通过解码来操作。

第三种解决方案

使用您的自定义序列化程序,如下所示:

  public class CustomJsonMediaFormatter : JsonMediaTypeFormatter
    {
     private JsonSerializerSettings _jsonSerializerSettings;

        public CustomJsonMediaFormatter ()
        {
            _jsonSerializerSettings = CreateDefaultSerializerSettings();
        }

  private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {

var contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders != null && contentHeaders.ContentLength == 0)
            {
                return GetDefaultValueForType(type);
            }

            // Get the character encoding for the content
            var effectiveEncoding = SelectCharacterEncoding(contentHeaders);

            try
            {
                using (var reader = (new StreamReader(readStream, effectiveEncoding)))
                {
                    var json = reader.ReadToEnd();
                    var jo = JObject.Parse(json);
                           // jo has got your value=xyz manipulate and feed back.
                }
             }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    相关资源
    最近更新 更多