實現POST以將JSON數據保存到本地文本文件的簡單方法是什麼?當我使用[FromBody]時,我一直得到空值,沒有它,它找不到POST資源。 基本上我想將原始數據保存到位於App_Data文件夾中的常規文本文件中。 謝謝。如何在web api中接收並保存JSON字符串
這裏是我的控制器
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":null,"file4":"AA","file5":"11111","file6":null,"file7":"11131","fil38":null,"files5":null}}
這是錯誤我在這行獲得:字符串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:
從小提琴手的原始代碼,但我得到了同樣的錯誤事件中,我只是把你好的字只有在身體..所以我不認爲這是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":null,"file4":"AA","file5":"11111","file6":null,"file7":"11131","fil38":null,"files5":null}}
請發表你的代碼的相關部分,所以我們可以嘗試看看有什麼不對。 – MattM
你能用你的控制器中的代碼編輯你的問題嗎?聽起來控制器方法就是我們試圖解決的問題。請包括您使用[FromBody]。 – MattM
嘗試將數據發佈到路由時,有很多事情可能會出錯。如果沒有至少一些服務器端代碼,我認爲我們不能說出發生了什麼。瞭解您如何發佈數據也是有幫助的,這樣我們就可以看到您提交請求的方式是否有問題。一般來說,雖然你應該能夠谷歌的WebAPI教程,將引導你通過這個。如果教程中存在令人困惑的部分,我們可以幫助填補空白。 – MattM