[英]Returning multiple values from WebApi (post) to AngularJs
I am using .net core C#, WebApi & AngularJs. 我正在使用.net核心C#,WebApi和AngularJs。
For saving data my Angularjs code makes a $http call to my WebApi. 为了保存数据,我的Angularjs代码对WebApi进行了$ http调用。 I can return single data from my api fine but not sure whats the best method to return multiple values here.
我可以很好地从api返回单个数据,但是不确定在这里返回多个值的最佳方法是什么。 I can make it comma separated and then return as well, but wanted to know if there is a better approach to this.
我可以将其用逗号分隔,然后再返回,但是想知道是否有更好的方法。
So basically when the API saves data to my db, I want to return a variable, boolean value if the save was successful and an exception message in case the save was not successfully. 因此,基本上,当API将数据保存到我的数据库时,我想返回一个变量,布尔值(如果保存成功)以及异常消息(以防保存不成功)。 Below is my code.
下面是我的代码。
AngularJs Code: AngularJs代码:
service.saveData(data).then(function (res) {
//get someDataToReturn, dataSaved & exception raised if any from db save here.
}, function (err) {
});
WebApi Code: WebApi代码:
[HttpPost("data/save")]
public async Task<IActionResult> SaveData([FromBody] List<UserData> data)
{
bool dataSaved = true;
string someDataToReturn = string.Empty;
//do some processing and updating someDataToReturn here
//Saving data to DB
dataSaved = SaveData(data);
//I want to return someDataToReturn, dataSaved(true or false) and exception raised from SaveData if any
return Ok(someDataToReturn);
}
//DB Call to save data
public bool SaveData(List<UserData> data)
{
try
{
foreach (var set in data)
{
//creating query etc
_db.Execute(query);
}
return true;
}
catch (SqlException ex)
{
}
return false;
}
Let me know the best approach for this. 让我知道最好的方法。
First of, you should check if the values in your request body is correctly populated. 首先,您应该检查请求正文中的值是否正确填充。
Take a look at DataAnnotations . 看一下DataAnnotations 。 You can use annotations to specify which properties in your model that are Required, Min and Maxlength etc.
您可以使用注释来指定模型中哪些属性是必需的,最小和最大长度等。
Here's an example on how to define a Name property to be required on the UserData class 这是一个有关如何定义UserData类所需的Name属性的示例
public class UserData
{
[Required]
public string Name { get; set; }
}
If the request model do not fulfill the specified rules set on the UserData class DataAnnotations, the context ModelState will be set to false and contain the DataAnnotations errors. 如果请求模型不满足UserData类DataAnnotations上设置的指定规则,则上下文ModelState将设置为false并包含DataAnnotations错误。 This can be used to determind if the current request is a bad request and return a proper http status code from that.
这可用于确定当前请求是否为错误请求,并从中返回正确的http状态代码。
[HttpPost("data/save")]
public async Task<IActionResult> SaveData([FromBody] List<UserData> data)
{
if (!ModelState.IsValid)
return BadRequest(ModelState); //will return a 400 code
...
Then regarding the SaveData method. 然后关于SaveData方法。 Capture the exception in the controller and return a proper status code from there
在控制器中捕获异常并从那里返回正确的状态代码
[HttpPost("data/save")]
public async Task<IActionResult> SaveData([FromBody] List<UserData> data)
{
if (!ModelState.IsValid)
return BadRequest(ModelState); //400 status code
try
{
SaveData(data);
}
catch(Exception e)
{
return InternalServerError(e); //500 status code
}
string someDataToReturn = string.Empty;
return Ok(someDataToReturn ); //200 status code
}
public void SaveData(List<UserData> data)
{
foreach (var set in data)
{
//creating query etc
_db.Execute(query);
}
}
you can create an entity and return it 您可以创建一个实体并将其返回
public class BaseResult{
public bool Result{get;set;}
public string Errors{get;set;}
}
or only 或仅
return Ok( new { result = dataSaved , error= exception.Message});
the standard way is: 标准方法是:
return 201 status code 返回201状态码
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
[HttpPost("data/save")]
public async Task<IHttpActionResult> SaveData([FromBody] List<UserData> data)
{
try
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
// return response of 201 if you created the resource successfully
// typically return this with a uri to the new resource
return Created("location", saveData(data));
}
catch (Exception)
{
return InternalServerError();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.