向IHttpActionResult返回BadRequest来自调用函数的Post函数

问题描述:

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

// 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"); 
} 

您不能返回错误请求从您的方法与CountryRegion返回类型。但是你可以用提升状态错误请求代码HttpResponseException这样的:

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

不知道,我undesrtand你正确的,但你可以做到这样:

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); 
      }