C# 从ajax调用WebApi时如何调试500内部服务器错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13259774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:58:11  来源:igfitidea点击:

How can I debug a 500 Internal Server Error when calling a WebApi from ajax?

c#jqueryasp.net-mvcasp.net-web-api

提问by Bruce C

I am receiving a 500 Internal Server Error in a MVC 4.5 WebApi project. I can successfully call my webservice with a GET and a GET with an Id. But, when I POST a file I am getting the error. I can set a breakpoint in Application_BeginRequest()and confirm that I am receiving first an OPTIONS request and then the POST. The method in the controller is not getting called and I have added an Application_Error()method to Global.asax.cs that does not get hit either. The html page is doing a CORS but I have already handled that using ThinkTecture.IdentityModel. I am following the code herefor the file upload.

我在 MVC 4.5 WebApi 项目中收到 500 内部服务器错误。我可以使用 GET 和带有 Id 的 GET 成功调用我的网络服务。但是,当我发布文件时,出现错误。我可以在其中设置断点Application_BeginRequest()并确认我首先收到一个 OPTIONS 请求,然后是 POST。控制器中的方法没有被调用,我已经Application_Error()向 Global.asax.cs添加了一个也不会被命中的方法。html 页面正在执行 CORS,但我已经使用ThinkTecture.IdentityModel处理。我正在按照此处的代码上传文件。

Any ideas?

有任何想法吗?

Here is the client code:

这是客户端代码:

    <script type="text/javascript">
        var UploadDocument = function () {
            var url = sessionStorage.getItem("url");
            var auth = sessionStorage.getItem("auth");
            var data = new FormData();

            jQuery.each($('#fileToUpload')[0].files, function (i, file) {
                data.append('file-' + i, file);
            });

            jQuery.support.cors = true;
            $.ajax({
                type: "POST",
                url: url,
                data: data,
                cache: false,
                processData: false,
                contentType: false,
                //dataType: "json",
                headers: { Authorization: 'Basic ' + auth },
                crossDomain: true,
                success: function (data, textStatus, jqXHR) {
                    alert('Success');
                },
                error: function (jqXHR, textStatus, errorThrown) { alert('Error: ' + textStatus + ' ' + errorThrown.message); }
            });
        };

    </script>

My controller code looks like this:

我的控制器代码如下所示:

    public int Post(HttpPostedFileBase FileToUpload)
    {
        // Do stuff with the file
    }

The request and response look like this:

请求和响应如下所示:

Request URL:http://localhost:51234/api/TaxDocument
Request Method:POST
Status Code:500 Internal Server Error

Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic YmNhbGxlbjpuZWxsYWM=
Connection:keep-alive
Content-Length:2054044
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryIGzPKhvRVwFXbupu
Host:localhost:51234
Origin:http://localhost:52386
Referer:http://localhost:52386/Upload.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4

Response Headers:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:52386
Cache-Control:no-cache
Content-Length:1133
Content-Type:application/json; charset=utf-8
Date:Tue, 06 Nov 2012 21:10:23 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpccHJvamVjdHNcU2F2ZU15VzJcU2F2ZU15VzIuV2Vic2VydmljZVxhcGlcVGF4RG9jdW1lbnQ=?=

采纳答案by Alexei Levenkov

To see all exceptions turn following setting on:

要查看所有例外情况,请打开以下设置:

  • VS 2013 (and below): Debug -> Exceptions -> CLR - check "when thrown".
  • VS 2015: Debug -> Windows -> Exception Settings -> CLR
  • VS 2013(及更低版本):调试 -> 异常 -> CLR - 检查“抛出时”。
  • VS 2015:调试 -> Windows -> 异常设置 -> CLR

You may need to uncheck "Tools->Options->Debugging->My code only" option if exception is thrown really outside of your code.

如果异常确实在您的代码之外抛出,您可能需要取消选中“工具->选项->调试->仅我的代码”选项。

回答by Protector one

You can try registering to the Errorevent of the HttpApplicationobject that's handling the request:

您可以尝试注册到正在处理请求ErrorHttpApplication对象的事件:

HttpApplicationReference.Error += ErrorHandler;

The method that handles the error:

处理错误的方法:

public void ErrorHandler(object sender, EventArgs e)
{
    System.Diagnostics.Debug.Write(
        ((System.Web.HttpApplication)sender).Server.GetLastError().ToString()
    );
}