【问题标题】:Model passed to web api is null if I pass base 64 encoded image in model如果我在模型中传递 base 64 编码图像,则传递给 web api 的模型为空
【发布时间】:2016-10-15 01:36:22
【问题描述】:

我通过 webapi 向服务器发送模型,模型包含 base 64 编码图像,但如果我发送没有编码字符串,那么在服务器端我将获得模型的所有其他属性,

但是当我在模型中包含 base64 编码的字符串时,整个模型将变为 null,

我在客户端使用 AngularJS,在服务器使用 .net WebApi

角度代码

var base64ImageString='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMg.......'
var req = {
 method: 'POST',
 url: 'myurl',
 data: { EncodedImage: base64ImageString,Name:'Rajiv' }
}

$http(req).then(function(){...}, function(){...});

服务器端代码

 public HttpResponseMessage Post([FromBody] UserInfo userInfo)
{
  //My Stuff
}

public class UserInfo
{
public String EncodedImage{get;set;}
public String Name{get;set;}
}

【问题讨论】:

    标签: javascript .net angularjs c#-4.0


    【解决方案1】:

    尝试先做一个请求,从后端获取一个空对象。在javascript中设置对象的属性,并将修改后的对象发送回服务器。

    $scope.model = {};
    
    $http.get(apiPath).then(function(result){
        $scope.model = result.data;
    });
    
    $scope.model.EncodedImage = base64ImageString;
    $scope.model.Name = "Rajiv";
    
    $http.post(apiPath, $scope.model).then(function(result){
        // ...
    });
    

    还要去掉后端的[FromBody],你的UserInfo类中的string应该用小写字母书写。

    【讨论】:

      【解决方案2】:

      您的图片是否太大?尝试上传较小的图像(大小为 100 KB)。如果可行,请在编码之前尝试压缩或降低图像的分辨率。这是一个例子:https://stackoverflow.com/a/20382559/1237117

      另一种选择是增加 Web API 的 json 大小限制。

      <configuration> 
         <system.web.extensions>
             <scripting>
                 <webServices>
                     <jsonSerialization maxJsonLength="50000000"/>
                 </webServices>
             </scripting>
         </system.web.extensions>
      </configuration> 
      

      【讨论】:

        【解决方案3】:

        您必须在 中增加 maxRequestLength

        我从forumAsp net得到了答案

        【讨论】:

          猜你喜欢
          • 2015-02-22
          • 2015-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多