【问题标题】:Create Custom Json Error in Asp.NET MVC在 Asp.NET MVC 中创建自定义 Json 错误
【发布时间】:2015-04-07 18:02:38
【问题描述】:

我正在使用 JavaScript 插件,如果出现错误,它期望格式如下;

{error: 'You are not allowed to upload such a file.'}

在我的 MVC Web API 中,我抛出了类似的错误;

 var error = string.Format("An error has been occured. Please try again later.");
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));

它在 HTTP 响应中表示,如下所示;

{"Message":"An error has been occured. Please try again later."}

如何实现以第一种方式返回?

【问题讨论】:

    标签: asp.net json asp.net-mvc asp.net-web-api


    【解决方案1】:

    你可以创建一个匿名对象

    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError,new { error = "your error message here!"}));
    

    【讨论】:

    • 这次它返回为 {"error":"your error message here!"} 并带有引号。我怎样才能消除它?
    • 为什么不用引号?
    • 我认为我使用的插件不接受格式以外的其他格式{error: 'You are not allowed to upload such a file.'} 请参阅plugins.krajee.com/file-input/demo#async-send
    • 您可以将 JSON 字符串解析为 Javascript 对象,以便在需要时使用它。示例: JSON.parse("{\"error\":\"你的错误信息在这里!\"}");
    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 2011-09-24
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多