Returning http status code from Web Api controller

前端 未结 13 1533
一生所求
一生所求 2020-11-27 10:01

I\'m trying to return a status code of 304 not modified for a GET method in a web api controller.

The only way I succeeded was something like this:

p         


        
13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 10:33

    I hate bumping old articles but this is the first result for this in google search and I had a heck of a time with this problem (even with the support of you guys). So here goes nothing...

    Hopefully my solution will help those that also was confused.

    namespace MyApplication.WebAPI.Controllers
    {
        public class BaseController : ApiController
        {
            public T SendResponse(T response, HttpStatusCode statusCode = HttpStatusCode.OK)
            {
                if (statusCode != HttpStatusCode.OK)
                {
                    // leave it up to microsoft to make this way more complicated than it needs to be
                    // seriously i used to be able to just set the status and leave it at that but nooo... now 
                    // i need to throw an exception 
                    var badResponse =
                        new HttpResponseMessage(statusCode)
                        {
                            Content =  new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json")
                        };
    
                    throw new HttpResponseException(badResponse);
                }
                return response;
            }
        }
    }
    

    and then just inherit from the BaseController

    [RoutePrefix("api/devicemanagement")]
    public class DeviceManagementController : BaseController
    {...
    

    and then using it

    [HttpGet]
    [Route("device/search/{property}/{value}")]
    public SearchForDeviceResponse SearchForDevice(string property, string value)
    {
        //todo: limit search property here?
        var response = new SearchForDeviceResponse();
    
        var results = _deviceManagementBusiness.SearchForDevices(property, value);
    
        response.Success = true;
        response.Data = results;
    
        var statusCode = results == null || !results.Any() ? HttpStatusCode.NoContent : HttpStatusCode.OK;
    
        return SendResponse(response, statusCode);
    }
    

提交回复
热议问题