1

我的 web api 控制器中有以下 web 方法

    public HttpResponseMessage PostMakeBooking(FacilityBookingRequest bookingRequest)
    {

        var returnStatus = HttpStatusCode.OK;
        var json = new JavaScriptSerializer().Serialize(bookingRequest);

        var response = Request.CreateResponse<CardholderResponse>(returnStatus, cardholderResponse);


        return response;

    }

当我从我的 .NET 应用程序进行此调用时,我的 json 字符串在我对其进行序列化时正确显示

{"correlationId":null,"RequestId":"7ec5092a-342a-4e32-9311-10e7df3e3683","BookingId":"BK-123102","CardholderId":"123456","BookingFrom":"\/Date(1370512706448)\/","BookingUntil":"\/Date(1370523506449)\/","DeviceId":"ACU-01-R2","Action":"Add","LoginId":"tester","Password":"tester"}

但是,当我从我的 php 脚本中调用时

public function web_request(){

    $guid   =self::getGUID();
    $replace = array("{","}");
    $guid  = str_replace($replace, "", $guid);

    $client = new Zend_Rest_Client("http://203.92.72.221");
    $request= new myZendCommon_FacilityBookingRequest();
    $request->RequestId         =$guid;
    $request->BookingFrom       ="27/03/2013 05:30";
    $request->BookingUntil      ="27/03/2013 06:30";
    $request->CardholderId      ="E0185963";
    $request->DeviceId          ="ACU-B2-01-R1";
    $request->BookingId         ="111";
    $request->Action            ="Add";
    $request->LoginId           ="tester";
    $request->correlationId     ="(null)";
    $request->Password          ="tester";


    $request = json_encode($request);

    $response = $client->restPost("/ibsswebapi/api/facilitybooking",$request);


    print_r($response);
    exit();

调用转到我的 web 方法,但是当我使用它序列化它时JavaScriptSerializer().Serialize(bookingRequest)

{"correlationId":null,"RequestId":null,"BookingId":null,"CardholderId":null,"BookingFrom":"\/Date(-62135596800000)\/","BookingUntil":"\/Date(-62135596800000)\/","DeviceId":null,"Action":null,"LoginId":null,"Password":null}

所有的值都是空的。

脚本有问题吗?

4

2 回答 2

2

我相信基兰是对的。不知道为什么有人觉得他的回答没有用。无论如何,我的理解是您正在创建一个 JSON 字符串并进行相同的表单发布。我猜在这种情况下,内容类型作为 application/www-form-urlencoded 发送,但请求正文是 JSON 字符串。您可以使用 Fiddler 查看 PHP 脚本如何发送请求。我没有 PHP 知识来告诉您如何发布 JSON,但我的猜测是,如果您只是删除 JSON 编码行$request = json_encode($request);,应该没问题。

从 ASP.NET Web API 的角度来看,如果请求有Content-Type: application/jsonheader 并且 body 有正确的 JSON,或者如果请求有Content-Type:application/www-form-urlencodedheader 并且 body 有 form url 编码的内容之类RequestId=7ec5092a-342a-4e32-9311-10e7df3e3683&BookingId=BK-123102的,web API 绝对没有问题捆绑。目前,请求未以正确的格式发送,以供 Web API 绑定。

于 2013-06-08T06:01:15.233 回答
1
  1. 您是否在请求中发送标头Content-Type:application/json

  2. 还要添加以下代码来捕获任何模型状态验证错误:

.

if (!ModelState.IsValid)
{
    throw new HttpResponseException(
         Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}
于 2013-06-08T01:16:55.350 回答