簡體   English   中英

asp.net Web API 2 AJAX 失敗

[英]asp.net Web API 2 AJAX fail

我使用 Web API 2 的測試從 AJAX 失敗方法返回狀態 200。

控制器:

[HttpPost]
    public HttpResponseMessage Post([FromBody] myData m)
    {
        return new HttpResponseMessage()
        {
            Content = new StringContent("TEST")
        };
    }

myData 類:

public class myData
{
    public int Id { get; set; }
    public string Name { get; set; }
}

從 HTML 調用 POST:

    <html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
    <script>
        var model = {
            Name: "Shyju",
            Id: 123
        };

        $.ajax({
        type: "POST",
        dataType: "text",
        data: JSON.stringify(model),
        url: "http://localhost:52884/api/contact",
        contentType: "application/json",
        crossDomain: true,
        success: function (response) {
            console.log(response)
        },
        error: function (response) {
            console.log("e : " + response)
        }
    });
    </script>
</body>

</html>

有誰知道為什么它不返回消息“TEST”?

謝謝

在 web api 2 中拋出 http 異常的好方法:

throw new HttpResponseException(
                    new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.InternalServerError,
                        ReasonPhrase = "Internal Server Error",
                        Content = new StringContent(JsonConvert.SerializeObject(myobject))
                    });

但是,值得注意的是一個簡單的 throw 異常語句會導致 500,它也會這樣做。 在我的示例中,它繞過了錯誤過濾和我的全局異常處理程序,只向 UI 返回一個錯誤狀態代碼和一些錯誤文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM