Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回JSON错误消息IActionResult_C#_Json_Asp.net Web Api - Fatal编程技术网

C# 返回JSON错误消息IActionResult

C# 返回JSON错误消息IActionResult,c#,json,asp.net-web-api,C#,Json,Asp.net Web Api,我有一个API控制器端点,如: public IHttpActionResult AddItem([FromUri] string name) { try { // call method return this.Ok(); } catch (MyException1 e) { return this.NotFound(); } catch (MyException2 e) {

我有一个API控制器端点,如:

public IHttpActionResult AddItem([FromUri] string name)
{
    try
    {
        // call method
        return this.Ok();
    }
    catch (MyException1 e)
    {
        return this.NotFound();
    }
    catch (MyException2 e)
    {
        return this.Content(HttpStatusCode.Conflict, e.Message);
    }
}
这将在正文中返回一个字符串,如
“这是您的错误消息”
,是否有方法返回带有“Content”的JSON

比如说,

{
  "message": "here is your error msg"
}

在您的情况下,您需要返回一个对象,它应该如下所示,我没有执行,但请尝试

public class TestingMessage
{
    [JsonProperty("message")]
    public string message{ get; set; }
}

public IHttpActionResult AddItem([FromUri] string name)
{
    TestingMessage errormsg=new TestingMessage();
    try
    {
        // call service method
        return this.Ok();
    }
    catch (MyException1)
    {
        return this.NotFound();
    }
    catch (MyException2 e)
    {
        string error=this.Content(HttpStatusCode.Conflict, e.Message);
        errormsg.message=error;
        return errormsg;
    }
}
1) 最简单的方法是:可以直接返回所需的任何对象,并将其序列化为JSON。它甚至可以是使用新{}创建的匿名类对象

(二)


只需将所需的对象模型构造为匿名对象并返回它

目前,您只返回原始异常消息

public IHttpActionResult AddItem([FromUri] string name) {
    try {
        // call service method
        return this.Ok();
    } catch (MyException1) {
        return this.NotFound();
    } catch (MyException2 e) {
        var error = new { message = e.Message }; //<-- anonymous object
        return this.Content(HttpStatusCode.Conflict, error);
    }
}
public IHttpActionResult附加项([FromUri]字符串名){
试一试{
//呼叫服务方法
返回这个;
}捕获(MyException1){
返回此.NotFound();
}捕获(MyException2e){

var error=new{message=e.message};//您尝试过JsonResult吗?在这里,最好的方法是使用ExceptionFilter并从返回ErrorResponse的通用模型there@frogcoder不,你能举个例子吗
return Json(new {message = e.Message});
public IHttpActionResult AddItem([FromUri] string name) {
    try {
        // call service method
        return this.Ok();
    } catch (MyException1) {
        return this.NotFound();
    } catch (MyException2 e) {
        var error = new { message = e.Message }; //<-- anonymous object
        return this.Content(HttpStatusCode.Conflict, error);
    }
}