how to return json error msg in asp.net web api?

后端 未结 5 1671
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 21:14

I would like to return a json errormessage but at the moment in fiddler I cannot see this in the json panel:

string error = \"An error just happened\";
JsonResul         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-03 22:20

    you can return JSON like below,

     return Request.CreateResponse(HttpStatusCode.BadRequest, response);
    

    I recommend to use IHttpActionResult on your method return type instead HttpResponseMessage, if your api's method return type is IHttpActionResult. you can return like;

     return Content(HttpStatusCode.InternalServerError, response);
    

    you can check also that link about best practice of error returning Especially @Daniel Little's answer is really useful.

    I know the answer added to late but maybe stand someone in good stead.

提交回复
热议问题