如何在web api中接收和保存JSON字符串

时间:2016-05-07 02:38:03

标签: c# json rest

实现POST以将JSON数据保存到本地文本文件的简单方法是什么?当我使用[FromBody]时,我一直得到空值,如果没有它,它就找不到POST资源。 基本上我想将原始数据保存到位于App_Data文件夹中的常规文本文件中。 谢谢。

这是我的控制器

public HttpResponseMessage Post([FromBody]string jsonstring)
      {        

          string json1 = HostingEnvironment.MapPath(@"~/App_Data/post.txt");
          string outp = jsonstring.ToString();
          File.WriteAllText(json1, outp);

          return new HttpResponseMessage()
         {
             StatusCode = HttpStatusCode.Created
         };

      }

并尝试我试图发布的json数据

{"system":{"programs":null,"info":null,"types":{"type1":"data1","type2":"data2",‌​"type3":"data3","type4":"data4","type5":"data5"},"name":"name1","name2":"name2","‌​sys":{"sys1":"info","sysv":"123"}},"files":{"file1":null,"file2":null,"file3":nul‌​l,"file4":"AA","file5":"11111","file6":null,"file7":"11131","fil38":null,"files5"‌​:null}} 

这是我在这一行得到的错误:string outp = jsonstring.ToString();

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=test
  StackTrace:
       at test.Controllers.testController.Post(String jsonstring) in c:\Users\test\test\Controllers\testController.cs:line 36
       at lambda_method(Closure , Object , Object[] )
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
       at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
  InnerException: 

来自fiddler的原始代码,但我得到了同样的错误事件我只是将Hello单词放在正文中..所以我不认为它的json相关错误

POST http://localhost:3281/api/test HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:3281
Content-Length: 357

{"system":{"programs":null,"info":null,"types":{"type1":"data1","type2":"data2",‌​"type3":"data3","type4":"data4","type5":"data5"},"name":"name1","name2":"name2","‌​sys":{"sys1":"info","sysv":"123"}},"files":{"file1":null,"file2":null,"file3":nul‌​l,"file4":"AA","file5":"11111","file6":null,"file7":"11131","fil38":null,"files5"‌​:null}} 

3 个答案:

答案 0 :(得分:0)

假设您将数据作为JSON对象而不是字符串发送,Post方法无法绑定您的对象(因为该方法需要字符串,而不是对象)。

另外,我相信您发布的JSON不是有效的JSON。尝试在路线工作时先发送更简单的东西。确保您发送的JSON有效(我使用jsonlint.com进行测试)。

以下是您可以发布的示例:

{
    "jsonstring": "foo"
}

我没有测试过这个,但是当你发布这个时,jsonstring应该正确绑定到Post方法中的参数,并且该字符串的值应该是“foo”。希望有所帮助。

答案 1 :(得分:0)

基本上您的请求需要使用 application / x-www-form-urlencoded

POST http://localhost:3281/api/test HTTP/1.1
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: localhost:3281
Content-Length: 357

答案 2 :(得分:0)

我找到了解决方案

  # ImagesController
  def create
    @image = Image.new(image_params)
    @image.save

    respond_to do |format|
      format.json { render :json => { url: Refile.attachment_url(@image, :image)} }
    end
  end

# Some Javascript

(function() {
  var host, uploadAttachment;

  document.addEventListener("trix-attachment-add", function(event) {
    var attachment;
    attachment = event.attachment;
    if (attachment.file) {
      return uploadAttachment(attachment);
    }
  });

  host = "/images";

  uploadAttachment = function(attachment) {
    var file, form, xhr;
    file = attachment.file;
    form = new FormData;
    form.append("Content-Type", file.type);
    form.append("image[image]", file);
    xhr = new XMLHttpRequest;
    xhr.open("POST", host, true);
    xhr.upload.onprogress = function(event) {
      var progress;
      progress = event.loaded / event.total * 100;
      return attachment.setUploadProgress(progress);
    };
    xhr.onload = function() {
      var href, url;
        url = href = JSON.parse(this.responseText).url;
        return attachment.setAttributes({
          url: url,
          href: href
        });
    };
    return xhr.send(form);
  };


}).call(this);