I'm working on asp.net mvc
webapi which returns result in json
format. I'm trying to set the Response.StatusCode
in which I'm partially succeed. When I hit the API on localhost
with Postman
it returns the status code and error message which I have set manually, but when I hit the API using published link it returns only StatusCode
.
public JsonResult Demo(string Fordate)
{
if (string.IsNullOrEmpty(Fordate))
{
errorMsg = "For Date is invalid, please correct";
ControllerContext.HttpContext.Response.StatusCode = Convert.ToInt32(HttpStatusCode.Unauthorized);
return Json(new { Response = errorMsg }, JsonRequestBehavior.AllowGet);
}
}
When I run above code on localhost
using Postman
it gives following output which is expected output:
But when I tried it with my published link it displays below Output in Postman
:
I have tried following line of code also but it does not work if there is a try-catch
block. If I put this line of code in try-catch
block it gives the error:
Cannot use local variable 'Response' before it is declared
Response.StatusCode = Convert.ToInt32(HttpStatusCode.Forbidden);
return Json(new { Response.StatusCode, Response = error }, JsonRequestBehavior.AllowGet);