在实体框架支持的 Web API 2 POST 调用中返回一个对象以及 409 冲突错误? [英] Return an object along with a 409 Conflict error in a Web API 2 POST call backed by Entity Framework?

查看:20
本文介绍了在实体框架支持的 Web API 2 POST 调用中返回一个对象以及 409 冲突错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C# 实体框架 Web API 2 控制器.目前,当尝试通过 POST 方法为主文本字段创建具有相同文本的对象时,我返回 409 Conflict error 作为 StatusCode 表明添加被视为重复的结果.

I have a C# Entity Framework Web API 2 controller. Currently when an attempt is made via the POST method to create an object with the same text for the main text field, I return a 409 Conflict error as an StatusCode result to indicate the addition is considered a duplicate.

我想做的是返回触发重复错误的服务器端对象.所以我需要类似于 Ok() 方法的东西,但需要一个变体,它返回 409 Conflict 错误作为 HTTP 状态代码而不是 HTTP OK 状态代码.

What I'd like to do is return the server side object that triggered the duplicate error too. So I need something akin to the Ok() method but a variant that returns a 409 Conflict error as the HTTP status code instead of an HTTP OK status code.

有这种事吗?我怎样才能做到这一点?如果我可以完成这项工作,客户端就不必在收到 409 冲突错误后对服务器进行后续 Get 调用以获取现有对象.

Is there such a thing? How can I do this? If I can make this work the client doesn't have to do a subsequent Get call to the server to get the existing object after receiving a 409 Conflict error.

这是当前的 POST 方法:

Here's the current POST method:

    public IHttpActionResult PostCanonical(Canonical canonical)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // Check for duplicate Canonical text for the same app name.
        if (db.IsDuplicateCanonical(canonical.AppName, canonical.Text))
        {
            // It's a duplicate.  Return an HTTP 409 Conflict error to let the client know.
            return StatusCode(HttpStatusCode.Conflict);
        }

        db.CanonicalSentences.Add(canonical);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = canonical.ID }, canonical);
    }

推荐答案

此解决方案适用于 WebApi v5 之前的版本,请参阅 this如果您使用的是 v5 或更高版本,请回答.

This solution is for WebApi prior v5, please see this answer if you are using v5 or above.

您可以返回一个 NegotiatedContentResult<T>,让您指定状态代码和要放入 http 消息正文的对象.

You could return a NegotiatedContentResult<T> that lets you specify the status code and an object to be put into the http message body.

把你的代码改成这样:

public IHttpActionResult PostCanonical(Canonical canonical)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // Check for duplicate Canonical text for the same app name.
    if (db.IsDuplicateCanonical(canonical.AppName, canonical.Text))
    {
        // It's a duplicate.  Return an HTTP 409 Conflict error to let the client know.
        var original = db.CanonicalSentences.First(c => c.ID == canonical.ID);
        return new NegotiatedContentResult<T>(HttpStatusCode.Conflict, original, this);
    }

    db.CanonicalSentences.Add(canonical);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = canonical.ID }, canonical);
}

或者也许将它包装成这样的扩展方法:

Or maybe wrap it an extension method like this:

public static class HttpActionResultExtensions {
    public static IHttpActionResult StatusCodeWithContent<T>(this ApiController @this, HttpStatusCode statusCode, T content) {
        return new NegotiatedContentResult<T>(statusCode, content, @this);
    }
}

然后像这样使用扩展:

public IHttpActionResult PostCanonical(Canonical canonical)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // Check for duplicate Canonical text for the same app name.
    if (db.IsDuplicateCanonical(canonical.AppName, canonical.Text))
    {
        // It's a duplicate.  Return an HTTP 409 Conflict error to let the client know.
        var original = db.CanonicalSentences.First(c => c.ID == canonical.ID);
        return StatusCodeWithContent(HttpStatusCode.Conflict, original)
    }

    db.CanonicalSentences.Add(canonical);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = canonical.ID }, canonical);
}

这篇关于在实体框架支持的 Web API 2 POST 调用中返回一个对象以及 409 冲突错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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