我正在尝试创建自己的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;
    }
}

所以这是我的代码....而且它有点工作,但事实并非如此。

这个'关键'是什么意思?我错过了什么,试图做什么?

请帮忙!

有帮助吗?

解决方案

找到我的答案 - >我不得不把网址放在“..”中。 (引号)否则它会尝试运行&符号之后的任何内容,作为命令或其他东西。

不确定原因,但是修复了它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top