如何将FormData读入WebAPI [英] How to read FormData into WebAPI

查看:1211
本文介绍了如何将FormData读入WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ASP.NET Web API框架的ASP.NET MVC WebApplication.

I have an ASP.NET MVC WebApplication where I am using the ASP.NET Web API framework.

JavaScript代码:

var data = new FormData();
data.append("filesToDelete", "Value");

$.ajax({    
    type: "POST",
    url: "/api/FileAttachment/UploadFiles?clientContactId=" + clientContactId,
    contentType: false,
    processData: false,
    data: data,
    success: function (result) {
        // Do something
    },
    error: function (xhr, status, p3, p4) {
        // Do something
    }
});

C#代码(WebAPI):

public void UploadFiles(int clientContactId) {
    if (!Request.Content.IsMimeMultipartContent()) {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var jsonContent = Request.Content.ReadAsStringAsync().Result;
}

如何基于Javascript FormData传递的键值对读取jsonContent?

How do I read jsonContent based on a key value pair passed by the Javascript FormData?

我尝试做JsonConvert.DeserializeObject<?>,但是它需要反序列化为特定类型.

I tried to do JsonConvert.DeserializeObject<?>, but it requires a particular type to deserialize into.

我想获取从Javascript FormData传递的键"filesToDelete"的值.

I want to get the value of the key "filesToDelete" passed from the Javascript FormData.

如何获得该值?

推荐答案

我要做的是:

客户端:而不是在查询字符串中传递clientContactId.将键值对附加到FormData对象本身中.将dataType设置为JSON.

Client Side: Instead of passing clientContactId in query string. Attach the key value pair in the FormData object itself. Set the dataType as JSON.

var data = new FormData();
data.append("filesToDelete", "Value");
data.append("clientContactId", 
(clientContactId != undefined || clientContactId != null) ? clientContactId : ''));

$.ajax({
        type: "POST",
        url: "/api/FileAttachment/UploadFiles",
        /* ONLY IF YOU ARE UPLOADING A FILE
        contentType: false,
        processData: false, */
        dataType: "JSON"
        data: data,
        success: function (result) {

        },
        error: function (xhr, status, p3, p4) {


        }
    });

服务器端::在服务器端,我们可以使用HttpContext.Current.Request来获取原始请求.

Server Side: At server side we can get the raw request using HttpContext.Current.Request.

因此,我们可以简单地使用HttpContext.Current.Request.Params["KeyValue"]FormData对象的键值来获取值.

So we can get the values by simply using the key values of FormData object inside HttpContext.Current.Request.Params["KeyValue"].

[HttpPost]
public void UploadFiles()
{
     var filesToDelete = HttpContext.Current.Request.Params["filesToDelete"];
     var clientContactId= HttpContext.Current.Request.Params["clientContactId"];

     //Your code here...
}

这篇关于如何将FormData读入WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆