我在做我自己的例外筛选。ASP.NET MVC附带了[handleError]属性。这很好->但它返回一些HTML错误视图。
因此,我想返回一些JSON错误消息。所以我自己做。
现在,在我测试我的URL之前,一切都很好。我总是出错。这是消息……
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;
}
}
这就是我的代码……这有点作用,但没有。
这个“钥匙”是什么意思?我错过了什么,想做什么?
请帮忙!