问题
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?
回答1:
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...
}
回答2:
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. Your WebApi controller method will look something like this:
public HttpResponseMessage Post([FromBody]WorkerAbsenceModel absence)
{
bool ok = svc.CreateWorkerAbsence(absence);
if (ok)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
回答3:
To get the "filesToDelete" value you can use 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"];
}
回答4:
You can create dynamic object
dynamic data = JsonConvert.DeserializeObject(jsonContent);
then you can access filesToDelete like
data.filesToDelete;
回答5:
I think this tutorial from the ASP.NET website might be what you are looking for:
Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data
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. 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:
[HttpPost]
public void UploadFiles(int clientContactId)
{
//access the 'clientContactId' input parameter
int id = clientContactId;
}
And your AJAX call will look something like this:
$.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. The Controller method could look something like this:
[HttpPost]
public void UploadFiles([FromBody] MyComplexType input)
{
}
And your AJAX call could look like:
$.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.
回答6:
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"];
来源:https://stackoverflow.com/questions/40798148/how-to-read-formdata-into-webapi