Вопрос

I'm trying to call a webservice in my C# ASP.Net MVC3 application. This is the source code:

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;
}

The code is returning a "400 Bad Request" error. This is how I'm doing it in javascript and it works.

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
    }
});

What modifications do I need to make to get the C# version working?

Это было полезно?

Решение

Just form your data (using Json.Net) as:

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

string data = JsonConvert.SerializeObject(obj);

Другие советы

I'd rather try to simplify your code using a WebClient and a JSON 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);
    }
}

Alternatively if you don't want to use the built-in .NET JavaScriptSerializer class you could use a third party one such as JSON.NET:

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

You are specifying the wrong content type. You are posting x-www-form-urlencoded data, but setting content-type to "application/json" Make your data match your content type, or vice-versa.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top