在实体框架支持的 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?(在实体框架支持的 Web API 2 POST 调用中返回一个对象以及 409 冲突错误?)
本文介绍了在实体框架支持的 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 冲突错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)