【问题标题】:Manipulating the received Json Data in Web API Controller在 Web API 控制器中操作接收到的 Json 数据
【发布时间】:2018-09-25 02:52:36
【问题描述】:

我正在从 Angular JS 控制器传递 Json 数据。 Json 数据包含两个名为 name 属性和 comment 属性的字符串以及一个文件列表。 angular的控制器代码如下:

app.controller("demoController", function ($scope, $http) {  
    //1. Used to list all selected files  
    $scope.files = [];  

    //2. a simple model that want to pass to Web API along with selected files  
    $scope.jsonData = {  
        name: "Sibnz",  
        comments: "This is a comment"  
    };  
    //3. listen for the file selected event which is raised from directive  
    $scope.$on("seletedFile", function (event, args) {  
        $scope.$apply(function () {  
            //add the file object to the scope's files collection  
            $scope.files.push(args.file);  
        });  
    });  

    //4. Post data and selected files.  
    $scope.save = function () {  
        $http({  
            method: 'POST',  
            url: "http://localhost:51739/PostFileWithData",  
            headers: { 'Content-Type': undefined },  

            transformRequest: function (data) {  
                var formData = new FormData();  
                formData.append("model", angular.toJson(data.model));  
                for (var i = 0; i < data.files.length; i++) {  
                    formData.append("file" + i, data.files[i]);  
                }  
                return formData;  
            },  
            data: { model: $scope.jsonData, files: $scope.files }  
        }).  
        success(function (data, status, headers, config) {  
            alert("success!");  
        }).  
        error(function (data, status, headers, config) {  
            alert("failed!");  
        });  
    };  
}); 

在 Web API 中,控制器我使用以下代码接收 JSON 数据:

 [HttpPost]
        [Route("PostFileWithData")]
        public async Task<HttpResponseMessage> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles");
            Directory.CreateDirectory(root);
            var provider = new MultipartFormDataStreamProvider(root);
            var result = await Request.Content.ReadAsMultipartAsync(provider);


            var model = result.FormData["jsonData"];

            var g = result.FileData;


            if (model == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            //TODO: Do something with the JSON data.


            //get the posted files
            foreach (var file in result.FileData)
            {
                //TODO: Do something with uploaded file.

                var f = file;

            }

            return Request.CreateResponse(HttpStatusCode.OK, "success!");
        }

当我调试代码时,我发现 JSON 数据正在填充 var model 和 var g 变量。我想从 Json 数据中提取名称和评论属性并将它们存储在数据库中。并且还想将文件复制到 /App_Data/Uploadfiles 目录并将文件位置存储在数据库中。

【问题讨论】:

    标签: asp.net angularjs json asp.net-web-api


    【解决方案1】:

    您需要在您的 Web API 中创建一个模型并将 JSON 数据反序列化为该模型,您可以为此使用 Newtonsoft.Json NuGet 包

    Install-Package Newtonsoft.Json

    class DataModel
    {  
        public string name { get; set; }  
        public string comments { get; set; }  
    } 
    

    在 Web API 控制器中

    using Newtonsoft.Json;
    
    HttpRequest request = HttpContext.Current.Request;
    var model = JsonConvert.DeserializeObject<DataModel>(request.Form["jsonData"]);
    
    // work with JSON data
    model.name
    model.comments
    

    处理文件

    // Get the posted files
    if (request.Files.Count > 0)
    {
        for (int i = 0; i < request.Files.Count; i++)
        {
            Stream fileStream = request.Files[i].InputStream;
            Byte[] fileBytes = new Byte[stampStream.Length];
            // Do something with uploaded file
            var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles/");
            string fileName = "image.jpg";
            File.WriteAllBytes(root + fileName, stampBytes);
            // Save only file name to your database
        }
    }
    

    【讨论】:

    • 如何将文件保存在目录中并在数据库中添加文件位置。 @Wael
    • 仍有一些垃圾文件存储在 App_Data/Uploadfiles @Wael
    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多