1

How can i return json result with a status code?

Here is my get method

 public JsonResult<List<AspNetCompaniesClass>> Get()
 {
   List<AspNetCompaniesClass> mItems = new List<AspNetCompaniesClass>();
   return Json(mItems);
 }
Dim
  • 433
  • 1
  • 9
  • 23
  • That will return 200 OK. What do you want to return instead ? also is your code compilable ? – Shyju Dec 18 '18 at 17:52
  • My code is an example, i want to create an if statement which it will return instead of 200 OK, example 400 bad request in else statement. – Dim Dec 18 '18 at 17:55
  • See this :https://stackoverflow.com/questions/11370251/return-json-with-error-status-code-mvc – I_Al-thamary Dec 18 '18 at 17:57
  • They sat to throw new exception throw new ValidationException(Json(response));, but i dont want status code 500 but 400 – Dim Dec 18 '18 at 17:59
  • @Dim: The first comment on the accepted answer of the linked duplicate may be of particular interest to you: https://stackoverflow.com/questions/11370251/return-json-with-error-status-code-mvc#comment20726712_11443564 In the answer, specifically focus on where they set `TrySkipIisCustomErrors` and set `StatusCode` on the `Response`. You can do this directly inside your controller action if you prefer. – David Dec 18 '18 at 18:03
  • Ok i found this on your link, var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NoContent,""); throw new HttpResponseException(errorResponse);. It really works, but i want to ask, is there any performace issue if i will throw new exception instead to return json result? – Dim Dec 18 '18 at 18:06
  • @Dim: Probably, but you don't *need* to throw an exception. Just set the status code on the response before returning. – David Dec 18 '18 at 18:07
  • Thank you david can you give me an example? – Dim Dec 18 '18 at 18:08
  • @Dim: `Response.StatusCode = HttpStatusCode.BadRequest;` – David Dec 18 '18 at 18:21
  • It doesnt work. do i need to place TrySkipIisCustomErrors before? – Dim Dec 18 '18 at 19:08

0 Answers0