1
我想讓我自己的ExceptionFilter。開箱即用,ASP.NET MVC帶有[HandleError]屬性。這太棒了 - >但它返回一些html錯誤視圖。需要一些自定義ASP.NET MVC的幫助IExceptionFilter
因此,我想返回一些json錯誤消息。所以我正在做我自己的。
現在,一切工作很好,直到我測試我的網址。我不斷收到錯誤。這是消息....
C:\Temp\curl-7.19.5>curl -i http://localhost:6969/search/foo?name=1234&key=test1xxx
HTTP/1.1 401 Unauthorized
Server: ASP.NET Development Server/9.0.0.0
Date: Mon, 14 Sep 2009 01:54:52 GMT
X-AspNet-Version: 2.0.50727
X-AspNetMvc-Version: 1.0
Cache-Control: private
Content-Type: application/json; charset=utf-8
Content-Length: 6
Connection: Close
"Hi StackOverflow"'key' is not recognized as an internal or external command,
operable program or batch file.
C:\Temp\curl-7.19.5>
好的 - 這沒有任何意義。讓我們讓一些代碼來解釋我想要做的,然後......
public class HandleErrorAsJson : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Snip normal checks and stuff...
// Assume we've figured out the type of error this is.
// I'm going to hardcode it here, right now.
int statusCode = 401;
string message = "Hi StackOverflow";
// Now prepare our json output.
filterContext.Result = new JsonResult
{
Data = message
};
// Prepare the response code.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = statusCode;
}
}
所以這是我的代碼....和它的工作八九不離十,但事實並非如此。
這個'關鍵'的意思是什麼?我錯過了什麼,試圖做什麼?
請幫忙!