未在 $ajax 方法中从 asp.net web api 后端获取错误消息

Not getting the error message from asp.net web api backend in $ajax method

我有一个简单的 ASP.Net Web API 方法 returns 像这样的 BadRequest ..

catch (Exception ex) 
            {
                Log.Error($"CreateRequest:requestedBy:{requestedBy.FirstName} {requestedBy.Surname} {requestedBy.EmailAddress} Message:{ex.Message} Stack Trace:{ex.ToString()}");
                return BadRequest(ex.Message);
                
            }

调用前端像这样以通常的方式捕获错误..

$.ajax({ 
                url: ResolveUrl(urlPath),
                data: jsonbody,
                type: 'POST',                                
                contentType: "application/json",
                success: function (data) {
                    //do something with data
                },
                error: function (response, textStatus, errorThrown) {                       
                      toastr.error(response.responseJSON || response.statusText);                        
                },
                complete: function (jxXHR, message)
                {
                    //do something here
                }
            });

问题是错误中响应对象中的 statusText:方法只有“BadRequest”,而不是从后端传入 ex.Message 的实际字符串。

这之前一直没有问题,并且已经这样做了很多年。 ex.Message 中的文本是“缺少资产类别”,但在 $.ajax 方法的响应对象上看不到它。

我是这样使用on error的

error: function (jqXHR, exception) {
var status =jqXHR.status; //400
var message = jqXHR.responseText;
var ex= exception; // 'abort' for example

....your code
}

https://dotnetfiddle.net/HwxlOF 我这样做。顺便说一下,使用 ajax 的成功来显示异常。

查看:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>

        $(function () {
            $("#theBtn").click(function () {
                alert("in the click...");
                $.ajax({
                    type: "GET",
                    url: "/api/values",  //I changed this url
                    async: false,
                    cache: false,
                    dataType: "json",
                    contentType: "application/json",
                    success: function (jsn) {
                        alert(jsn);
                    },
                    error: function (error) {
                        alert("error");
                        console.log(error);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="button" id="theBtn" value="Click to start ajax" />
    </div>
</body>
</html>

API:

public class ValuesController : ApiController
{
    public HttpResponseMessage Get()
    {
        try
        {
            throw new Exception("Luke Perrin shows exception");
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.OK, ex.Message);
         }
    }

问题是 web.config 覆盖了错误处理。这就是为什么我没有看到原始错误而是看到 html 内容的原因。它有这个现在被注释掉了。

 <httpErrors errorMode="Custom" existingResponse="Replace"> 
      <clear />
      <remove statusCode="400" />
      <remove statusCode="401" />
      <remove statusCode="404" />
      <remove statusCode="500" />
      <error statusCode="400" path="500.html" responseMode="File" />
      <error statusCode="401" path="500.html" responseMode="File" />
      <error statusCode="404" path="404.html" responseMode="File" />
      <error statusCode="500" path="500.html" responseMode="File" />
    </httpErrors>