Asp.net mvc 将BadRequest从被调用函数返回到IHttpActionResult Post函数

Asp.net mvc 将BadRequest从被调用函数返回到IHttpActionResult Post函数,asp.net-mvc,asp.net-web-api,Asp.net Mvc,Asp.net Web Api,我如何在Post IHttpActionResult函数return BADDREQUEST中调用函数,而不必将函数作为IHttpActionResult返回?假设我有以下功能: // POST api/Country [ResponseType(typeof(CountryRegion))] public IHttpActionResult PostCountryRegion(CountryRegion countryregion) { countryregion = checkAnd

我如何在Post IHttpActionResult函数return BADDREQUEST中调用函数,而不必将函数作为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");
}
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
  ReasonPhrase = "CountryCriteria specified does not exist"
});

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

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

    //check stuff
    //somethings wrong
    return BadRequest("CountryCriteria specified does not exist");
}
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
  ReasonPhrase = "CountryCriteria specified does not exist"
});

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

    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);
            }
公共异步任务后置集(集合)
{
如果(!ModelState.IsValid)
{
返回请求(ModelState);
}
尝试
{
if(ItemExist(sets.SetID,sets.ItemName)=false)
{
db.Sets.Add(套);
等待db.saveChangesSync();
}
其他的
{
//在这里您返回HttpResponseException
var resp=新的HttpResponseMessage(HttpStatusCode.BadRequest);
resp.Content=新的StringContent(“аааааааааааааааа;
抛出新的HttpResponseException(resp);
}
}
catch(DbEntityValidationException dbEx)
{
foreach(dbEx.EntityValidationErrors中的var validationErrors)
{
foreach(validationErrors.validationErrors中的var validationError)
{
Trace.TraceInformation(“属性:{0}错误:{1}”,validationError.PropertyName,validationError.ErrorMessage);
}
}
}
返回CreatedAtRoute(“PreppApi”,new{id=sets.id},sets);
}