![](/img/trans.png)
[英]WEB API + ASP.NET trying to display data from WEB.API in json format
[英]How to Display custom errors JSON Result in WEB.API
我是Web.API
。 我有網址
http:// localhost:21923 / communities / getPost / locationID = 1 。
如果可以的話,我在上面的URL中錯誤地使用了location
而不是locationID
,它顯示了Error 。 相反,我需要返回以下JSON結果。
{ "message": "Parameter missmatch", "errorCode": 404 (or) something else, "Status": false }
如何顯示JSON結果而不是Web.API中的預定義錯誤?
嘗試在Global.asax中使用Application_Error處理程序: https : //msdn.microsoft.com/zh-cn/library/24395wz3.aspx
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// Handle HTTP errors by sending the JSON (only for Http Error)
if (exc.GetType() == typeof(HttpException))
{
// The Complete Error Handling Example generates
// some errors using URLs with "NoCatch" in them;
// ignore these here to simulate what would happen
// if a global.asax handler were not implemented.
if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
return;
//Return a JSON object
Response.Write(JsonConvert.SerializeObject(new
{
"message": "Parameter missmatch",
"errorCode": "404 (or) something else",
"Status": false
})
);
}
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>\n");
Response.Write(
"<p>" + exc.Message + "</p>\n");
Response.Write("Return to the <a href='Default.aspx'>" +
"Default Page</a>\n");
// Log the exception and notify system operators
ExceptionUtility.LogException(exc, "DefaultPage");
ExceptionUtility.NotifySystemOps(exc);
// Clear the error from the server
Server.ClearError();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.