ASP.NET WebApi ApiController change StatusCode

web api return status code with data
web api return status code with message
ihttpactionresult return object
ihttpactionresult return json
c# web api return http status code
web api return httpresponsemessage or object
ihttpactionresult not found
.net core web api return status code with message

I have a RESTful service in .NET and i would like all actions return an object of type JsonResult, JsonResult is an object defined by me like this:

public class JsonResult<T>
{
    public Notify Notify {get; set;}
    public T Data {get; set;}

    public static CreateResponse(T Data, Notify Notify = null, HttpStatusCode Code = HttpStatusCode.OK)
    {
        //Code param not manage, at the moment

        return new JsonResult<T>
        {
            Data = Data,
            Notify = Notify
        };

    }
}

public class Notify
{
    public string Message {get; set;}
    public Severity Severity {get; set;}
}

public enum Severity
{
    Error,
    Info,
    Warning,
    Fatal,
}

so at the moment i have actions look like that:

public JsonResult<string> Get()
{

    return JsonResult<string>.CreateResponse("Ciao Mondo!");
}

it works and i like this form 'cause when i read the firm i already know what i want to return to the client (JsonResult, T is the type of my data)... but the problem is when i want to manage the status code.

Before to create this new project, to manage the status code i used the HttpResponseMessage and the method Request.CreateResponse to return some data to the client:

public HttpResponseMessage Get()
{

    return Request.CreateResponse(HttpStatusCode.BadRequest, "Ciao Mondo!");
}

but i don't like that 'cause it is not immediate to know the returned type.

so... my question is... how can i manage the status code into my JsonResult.CreateResponse(T, Notify[, HttpStatusCode]) method?

this method is moved into an CustomApiController (inherits from ApiController), so i have HttpContext and Request available.

Thanks so much to all

You could call Content which accepts a HttpStatusCode as well as a generic object. It does require you to change your method's return type to IHttpActionResult which is generally preferred.

public IHttpActionResult Get()
{
  if(someErrorCondition)
     return Content(HttpStatusCode.BadRequest, JsonResult<string>.CreateResponse("Ciao Mondo!"));
  return Ok(JsonResult<string>.CreateResponse("Ciao Mondo!"));
}

Returning http status code from Web Api controller, I did not know the answer so asked the ASP.NET team here. So the trick is to change the signature to HttpResponseMessage and use Request.​CreateResponse  Good morning everyone, and welcome to the new HTTP Status Codes in ASP.NET Web API tour here at Exception Not Found! My name is Reggie, and I'll be your tour guide today. Those of you who have taken our Exception Handling tour, welcome back! For those of you who are new to our facility, thank you for visiting us.

Its preferred to use IHttpActionResult, don't forcefully define it to JsonResult. This should be configurable through content-negotiation.

You can try as below:

     public IHttpActionResult Get()
     {
      if(error)
          BadRequest("Bad Request !!");
       return Ok("Ciao Mondo!");
     }

ApiController.StatusCode(HttpStatusCode) Method (System.Web , Creates a with the specified status code. Http. Assembly: Microsoft.AspNetCore​.Mvc.WebApiCompatShim.dll Applies to. ASP.NET Core. 2.2 2.1 2.0 1.1 1.0  Microsoft’s ASP.NET Web API is a lightweight framework you can use to build stateless RESTful services that run on HTTP.

Your answer were be very helpful. I was looking for another solution, but you gave me a good idea and i have found this solution:

public class CustomApiController : ApiController
{

    public class JsonResult<Target> : NegotiatedContentResult<Target>
    {
        public JsonResult(HttpStatusCode statusCode, Json<Target> content, ApiController controller) : base(statusCode, content.Data, controller)
        {

            this.Content = content;
        }

        public JsonResult(HttpStatusCode statusCode, Target content, ApiController controller) : base(statusCode, content, controller)
        {

        }

        public JsonResult(HttpStatusCode statusCode, Target content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
            : base(statusCode, content, contentNegotiator, request, formatters)
        {

        }

        public new Json<Target> Content { get; private set; }

    }


    public JsonResult<Target> CreateResponse<Target>(Target Data, string Notify, HttpStatusCode Code = HttpStatusCode.OK)
    {
        Json<Target> json = new Json<Target>
        {
            Notify = Notify,
            Data = Data
        };

        return new JsonResult<Target>(Code, json, this);
    }

}

so i can inherit from CustomApiController and write action like that:

    public JsonResult<IEnumerable<string>> Get(bool test)
    {
        if (test)
        {
            return this.CreateResponse(new string[] { "test1", "test2", "test3" } as IEnumerable<string>, null, System.Net.HttpStatusCode.OK);
        }
        else
        {
            return this.CreateResponse(new string[] { "test1", "test2", "test3" } as IEnumerable<string>, null, System.Net.HttpStatusCode.BadRequest);
        }
    }

thanks a lot!

Action Results in Web API 2, A Web API controller action can return any of the following: void , Web API simply returns an empty HTTP response with status code 204 (No  For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult. You can then return a built in IHttpActionResult implementation like Ok, BadRequest, etc ( see here) or return your own implementation.

HTTP Status Codes in ASP.NET Web API, ASP.NET Web API can return any of those codes, though the more common ones have One status code you could return is 400 Bad Request, as this implies that the public class MovieController : ApiController { [HttpPost] all you would need to do is change the return type and return statement, like so: An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC. You can create your own class that implements IHttpActionResult or use various methods of ApiController class that returns an object that implement the IHttpActionResult.

create Web API response, It will send 204 "No Content" status code as a response when you send HTTP DELETE Web API controller always returns an object of HttpResponseMessage to the hosting class which is more or less similar to ActionResult class in ASP. As per my knowledge, ASP.NET Core doesn’t have inbuilt methods for all the HTTP status codes. Sometimes, you will need to return status codes without such an inbuilt method. Status codes without such a shortcut method can be returned through the StatusCode method which accepts an integer as an input. You can pass the status code number.

How to return a result with HttpStatusCode in Web API, I have a post method below, How to retunr the result with Status Code? HttpPost] public HttpResponseMessage  Select the ASP.NET Core Web Application template and click Next. Name the project TodoApi and click Create. In the Create a new ASP.NET Core Web Application dialog, confirm that .NET Core and ASP.NET Core 2.2 are selected. Select the API template and click Create. Don't select Enable Docker Support. Open the integrated terminal.

Comments
  • If you're returning a response, the implication is that the request found the entity that was requested, so the only reasonable status code is 200. Which status code other than 200 OK would you want to return and why?
  • it isn't always true... if i cannot (for thousand reasons) execute a part of my code i would like to manage the error and not throw it to the client. for example: i have caught a timeout and i want generate a notify that explain it, this wouldn't say that i have a good response and my request is satisfied.