首页 > 解决方案 > Laravel API 返回空白/空到 RestSharp C#

问题描述

我使用 Laravel 作为与我的 C# 应用程序通信的 Web API。

我正在尝试发出帖子请求:

if ($validate){
        // Store query results in a variable
        $user = Login::where([
                ['BR_ID', $BR_ID],
                ['ClientID', $ClientID],
                ['ClientChkID', $ClientChkID],
                ['LastName', $LastName]
        ])->get();
        // Format contact number
        $ContactNo = $user[0]->ContactNo;
        $otpController = new \App\Http\Controllers\OTPController();
        $phone = $otpController->CheckContactValidity($ContactNo);
        // Append formatted number to laravel's collection object
        $user[0]->ValidContactNo = $phone;

        // send back a response
        return response()->json($user[0], 200);
} else {
        return response()->json(["error"=>"Client does not exist"], 204);
}

if 语句中的代码运行良好,一切正常。但是,else 部分根本不返回任何内容。

基本上,该行return response()->json(["error"=>"Client does not exist"], 204);总是返回""而不是{ "error":"Client does not exist" }

标签: c#laravel

解决方案


这是无稽之谈。204 状态码是一个无内容响应,那么为什么要返回一些东西呢?

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success

您可以通过以下方式检查响应代码

        $.ajax({
        url: "/test",
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function(res) {
        }
        })
        .done(function ( data, textStatus, jqXHR) {
                console.log(jqXHR.status); // 204
        });

推荐阅读