繁体   English   中英

返回JSON错误消息,IActionResult

[英]Returning JSON error message, IActionResult

我有一个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);
    }
}

这将返回正文中的字符串,如"here is your error msg" ,有没有办法返回带有'内容'的JSON?

例如,

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

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

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

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 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。 它甚至可以是使用new {}创建的匿名类对象

2)

return new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
        Content = new ObjectContent(typeof(ErrorClass), errors, new JsonMediaTypeFormatter())
    };
return Json(new {message = e.Message});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM