繁体   English   中英

调用Web服务“ 400错误的请求”错误

[英]Calling web service “400 Bad Request” error

我正在尝试在我的C#ASP.Net MVC3应用程序中调用Web服务。 这是源代码:

public string getCourseSchedule()
{
    string url = "http://192.168.1.198:15014/ShoppingCart2/CourseSchedule";
    string data = "Months&StatesMX&Zip=&Miles=&ProgramCodes=&EventCode=&PaginationStart=1&PaginationLimit=3";
    byte[] bytes          = Encoding.UTF8.GetBytes(data);
    var myReq             = (HttpWebRequest)WebRequest.Create(url);
    myReq.Method          = "POST";
    myReq.ContentLength   = data.Length;
    myReq.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
    string responseString = "";

    using (Stream requestStream = myReq.GetRequestStream())
    {
        requestStream.Write(bytes, 0, bytes.Length);
    }

    using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
    {
        HttpStatusCode statusCode = response.StatusCode;
        if (statusCode == HttpStatusCode.OK)
        {
            responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
    }
    return responseString;
}

该代码返回“ 400 Bad Request”错误。 这就是我在javascript中执行此操作的方式,并且有效。

Mexico_Schedule: {"Months": null,
                  "States": [{"State: "MX"}],
                  "Zip": "",
                  "Miles": "",
                  "ProgramCodes": null,
                  "EventCode": null
                  "PaginationStart": 1,
                  "PaginationLimit": 3
};

$.ajax({
    async:       true,
    cache:       false,
    type:        'POST',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    url:         "http://192.168.1.198:15014/ShoppingCart2/CourseSchedule",
    data:        JSON.stringify(Mexico_Schedule),
    dataType:    'json',
    success: function (data) {
        console.log('Fired when the request is successful');
        // Do something with results
    }
});

为了使C#版本正常工作,我需要进行哪些修改?

只需将您的data (使用Json.Net )形成为:

var obj = new
{
    States = new[] { new{ State = "MX" } },
    Zip = "",
    Miles = "",
    PaginationStart = 1,
    PaginationLimit = 3
};

string data = JsonConvert.SerializeObject(obj);

我宁愿尝试使用WebClientJSON serializer程序来简化您的代码:

public string getCourseSchedule()
{
    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "apoplication/json";
        var url = "http://192.168.1.198:15014/ShoppingCart2/CourseSchedule";
        var json = new JavaScriptSerializer().Serialize(new
        {
            States = new[] { new { State = "MX" } },
            Zip = "",
            Miles = "",
            PaginationStart = 1,
            PaginationLimit = 3
        });
        byte[] data = Encoding.UTF8.GetBytes(json);
        byte[] result = client.UploadData(url, data);
        return Encoding.UTF8.GetString(result);
    }
}

另外,如果您不想使用内置的.NET JavaScriptSerializer类,则可以使用第三方,例如JSON.NET:

string json = JsonConvert.SerializeObject(new
{
    States = new[] { new { State = "MX" } },
    Zip = "",
    Miles = "",
    PaginationStart = 1,
    PaginationLimit = 3
});

您指定了错误的内容类型。 您正在发布x-www-form-urlencoded数据,但是将content-type设置为“ application / json”使数据与您的内容类型匹配,反之亦然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM