Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

c# - How to read FormData into WebAPI

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

Javascript code:

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):

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?

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

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

How can I get this value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What I would Do is:

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) {


        }
    });

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

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...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...