我正在尝试制作自己的 ExceptionFilter。开箱即用的 ASP.NET MVC 带有 [HandleError] 属性。这很棒 -> 但它会返回一些 html 错误视图。
因此,我想返回一些 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;
}
}
所以这就是我的代码....它有点工作,但它不是。
这个“关键”是什么意思?我错过了什么,试图做什么?
请帮忙!