在操作中使用IActionResult作为结果类型的优势 [英] Advantage of using IActionResult as result type in Actions

查看:756
本文介绍了在操作中使用IActionResult作为结果类型的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用IActionResult作为WebApi控制器的返回类型而不是要返回的实际类型有什么好处或建议?

What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?

我见过的大多数示例都返回IActionResult,但是当我构建第一个站点时,我只将View Model类用作返回类型....现在,我觉得我做错了所有事情!

Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!

推荐答案

主要优点是您可以返回错误/状态代码或重定向/资源URL.

The main advantage is that you can return error/status codes or redirects/resource urls.

例如:

public IActionResult Get(integer id) 
{
    var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

    if(user == null) 
    {
        // Returns HttpCode 404
        return NotFound();
    }

    // returns HttpCode 200
    return ObjectOk(user);
}

public IActionResult Create(User user) 
{
    if(!ModelState.IsValid) 
    {
        // returns HttpCode 400
        return BadRequest(ModelState);
    }

    db.Users.Add(user);
    db.SaveChanges();

    // returns HttpCode 201
    return CreatedAtActionResult("User", "Get", new { id = user.Id} );
}

这篇关于在操作中使用IActionResult作为结果类型的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆