简体   繁体   English

如何将FormData读入WebAPI

[英]How to read FormData into WebAPI

I have an ASP.NET MVC WebApplication where I am using the ASP.NET Web API framework. 我有一个ASP.NET MVC WebApplication,我正在使用ASP.NET Web API框架。

Javascript code: 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# code (WebAPI): C#代码(WebAPI):

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

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

How do I read jsonContent based on a key value pair passed by the Javascript FormData? 如何根据Javascript FormData传递的键值对读取jsonContent

I tried to do JsonConvert.DeserializeObject<?> , but it requires a particular type to deserialize into. 我试图做JsonConvert.DeserializeObject<?> ,但它需要一个特定的类型来反序列化。

I want to get the value of the key "filesToDelete" passed from the Javascript FormData. 我想获取从Javascript FormData传递的键"filesToDelete"的值。

How can I get this value? 我怎样才能获得这个价值?

What I would Do is: 我会做的是:

Client Side : Instead of passing clientContactId in query string. 客户端 :而不是在查询字符串中传递clientContactId。 Attach the key value pair in the FormData object itself. 在FormData对象本身中附加键值对。 Set the dataType as JSON. 将dataType设置为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) {


        }
    });

Server Side: At server side we can get the raw request using HttpContext.Current.Request . 服务器端:在服务器端,我们可以使用HttpContext.Current.Request获取原始请求。

So we can get the values by simply using the key values of FormData object inside HttpContext.Current.Request.Params["KeyValue"] . 因此,我们可以通过简单地使用HttpContext.Current.Request.Params["KeyValue"]FormData对象的键值来获取值。

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

     //Your code here...
}

If you want to send data with JSON like that you should define a model in C# that matches the model you're passing back in JSON. 如果要使用JSON发送数据,则应在C#中定义一个与您在JSON中传回的模型匹配的模型。 Your WebApi controller method will look something like this: 您的WebApi控制器方法将如下所示:

    public HttpResponseMessage Post([FromBody]WorkerAbsenceModel absence)
    {
        bool ok = svc.CreateWorkerAbsence(absence);
        if (ok)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

To get the "filesToDelete" value you can use JSON.NET . 要获取“filesToDelete”值,您可以使用JSON.NET the code: 代码:

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

            JObject jObject = JObject.Parse(jsonContent);
            var filesToDelete = jObject["filesToDelete"];    
        }  

You can create dynamic object 您可以创建dynamic对象

dynamic data = JsonConvert.DeserializeObject(jsonContent);

then you can access filesToDelete like 那么你可以像访问filesToDelete一样

data.filesToDelete;

I think this tutorial from the ASP.NET website might be what you are looking for: 我认为ASP.NET网站上的这个教程可能就是你想要的:

Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data 在ASP.NET Web API中发送HTML表单数据:表单 - urlencoded数据

Based on your sample code I'm not sure if you need a complex type from the form data or just a single integer based on the UploadFiles(int clientContactId) method in your API Controller. 基于您的示例代码,我不确定您是否需要表单数据中的复杂类型,或者只需要基于API控制器中的UploadFiles(int clientContactId)方法的单个整数。 The signature makes it seem like you're just trying to pass a single integer. 签名使您看起来只是想传递一个整数。 If that is the case, your API Controller method could look like this: 如果是这种情况,您的API控制器方法可能如下所示:

[HttpPost]
public void UploadFiles(int clientContactId)
{
    //access the 'clientContactId' input parameter
    int id = clientContactId;
}

And your AJAX call will look something like this: 你的AJAX调用看起来像这样:

$.ajax({
    url: '/api/controller/UploadFiles', //your app url
    type: 'POST',
    data: { clientContactId: 12345 },
    dataType: 'json',
    success: function (result) {
        //do whatever
    },
    error: function (result) {
        //do whatever
    }
});

If you already have the data formatted as JSON in your JavaScript, you can send it in the body of the requests. 如果您已经在JavaScript中将数据格式化为JSON,则可以在请求正文中发送。 The Controller method could look something like this: Controller方法看起来像这样:

[HttpPost]
public void UploadFiles([FromBody] MyComplexType input)
{

}

And your AJAX call could look like: 你的AJAX调用看起来像:

$.ajax({
    url: '/api/controller/UploadFiles', //your app url
    type: 'POST',
    data: JSON.stringify(input),
    dataType: 'json',
    success: function (result) {
        //do whatever
    },
    error: function (result) {
        //do whatever
    }
});

Check out the tutorial I linked to above though, I think that may explain things a bit better for you. 看看我上面链接的教程,我认为这可能会为你解释一些更好的东西。

Please use the below for get the value in the controller, 请使用以下内容获取控制器中的值,

var filesToDelete = HttpContext.Current.Request.Params["filesToDelete"];
var clientContactId= HttpContext.Current.Request.Params["clientContactId"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM