如何在Web API中接收表单数据和处理数据 [英] How to receive form data and process the data in Web API
问题描述
我是Web API的新手,这里将Angular 4应用程序中的表单数据发送到Web API.
I am new to web API ,Here sending the form data from Angular 4 application to web API.
表单数据包含作为mFormData的用户注册详细信息和作为mImage的用户图像.
the form data contains a user registration details as mFormData and the user image as mImage .
我要将图像存储在系统文件夹ex中:D:/uplodedImages并且需要将所有用户详细信息存储在数据库中.
I want to store the image in the system folder ex : D:/uplodedImages and need to store all the user details in database .
我正在努力做上述事情.
I am struggling to do the above things .
service.ts(角度4)
service.ts(angular 4)
CreateNewComitteeMember(mFormData, mImage) {
const formData: FormData = new FormData();
formData.append('ImageFile', mImage, mImage.name);
formData.append('mFormData', JSON.stringify(mFormData));
return this.http.post(this.BASE_URL + `/api/CreateNewComitteeMember`, formData)
}
API
[AllowAnonymous]
[HttpPost]
[Route("api/CreateNewComitteeMember")]
public Task<HttpResponseMessage> CreateNewComitteeMember()
{
//How to do the remaining things here.
}
谁能帮我解决这个问题.
can anyone help me to solve this .
推荐答案
您可以通过访问附加数据时使用的名称来简单地获取数据.
You can simply get the data by accessing the name that you used while appending your data.
但是,由于ASP.NET无法识别Java对象.您将需要序列化"mFormData".因此,请求将像这样更改.
But since java object will not be recognized by ASP.NET. You will need to serialize the "mFormData". So, the request will change like this.
formData.append('mFormData', JSON.stringify(mFormData));
现在,在Web API中,创建一个复制"mFormData"的模型,将其称为MFormData.
Now in you Web API create a model that replicates your "mFormData", lets call it MFormData.
示例
public class MFormData
{
public string Name {get; set;}
public int Age {get; set;}
public string Xyz {get; set;}
public string ImageUrl {get; set;}
...
}
现在,在您的API中,您可以像这样访问数据.
Now, In your API you can access the data like this.
[AllowAnonymous]
[HttpPost]
[Route("api/CreateNewComitteeMember")]
public Task<HttpResponseMessage> CreateNewComitteeMember()
{
var imageData = HttpContext.Current.Request.Params["mImage"];
var formData = new JavaScriptSerializer()
.Serialize<MFormData>(HttpContext.Current.Request.Params["mFormData"]);
try
{
//Function to save the file and get the URL
formData.ImageUrl = new ApplicationBussinessLayer().SaveFileInDir(imgeData);
//Function to save data in the DB
var saveData = await new AppicationBussinessLayer().SaveUserInfo(formData);
}
catch(Exception ex)
{
return Request.Create(HttpStatusCode.Code, "Some error");
}
return Request.Create(HttpStatusCode.OK, "Data Saved");
}
这篇关于如何在Web API中接收表单数据和处理数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!