将BadRequest返回给IHttpActionResult来自被调用函数的Post函数

时间:2013-11-26 06:32:35

标签: asp.net-mvc asp.net-web-api

如何在Post IHttpActionResult函数中调用函数返回BadRequest而不必将函数作为IHttpActionResult返回?说我有以下功能:

// POST api/Country
[ResponseType(typeof(CountryRegion))]
public IHttpActionResult PostCountryRegion(CountryRegion countryregion)
{
    countryregion = checkAndChangeSomeStuff(countryregion);

    db.CountryRegions.Add(countryregion);
    db.SaveChanges();

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

而不是默认:

// POST api/Country
[ResponseType(typeof(CountryRegion))]
public IHttpActionResult PostCountryRegion(CountryRegion countryregion)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.CountryRegions.Add(countryregion);
    db.SaveChanges();

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

我希望checkAndChangeSomeStuff()是这样的:

protected internal CountryRegion checkAndChangeSomeStuff(CountryRegion countryregion)
{
    //do stuff

    //check stuff
    //somethings wrong
    return BadRequest("CountryCriteria specified does not exist");
}

2 个答案:

答案 0 :(得分:1)

您无法使用CountryRegion返回类型从您的方法返回BadRequest。但是您可以使用BadRequest状态代码引发HttpResponseException,如下所示:

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
  ReasonPhrase = "CountryCriteria specified does not exist"
});

答案 1 :(得分:0)

不确定我理解你是否正确,但你可以这样做:

    public async Task<IHttpActionResult> PostSets(Sets sets)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                try
                {
                    if (ItemExist(sets.SetID, sets.ItemName) == false)
                    {
                        db.Sets.Add(sets);
                        await db.SaveChangesAsync();
                    }
                    else
                    {
//Here you return HttpResponseException
                        var resp = new HttpResponseMessage(HttpStatusCode.BadRequest);
                        resp.Content = new StringContent("Такой продукт уже добавлен.");
                        throw new HttpResponseException(resp);
                    }
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }

                return CreatedAtRoute("PreppApi", new { id = sets.Id }, sets);
            }