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

查看:17
本文介绍了在 Actions 中使用 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} );
}

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

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