1

我正在尝试构建一个 GET 网络服务,该服务将从网站 1 发起 GET 请求...将该请求发送到网站 2,网站 2 将通过发送对象列表来响应。我使用 Json.net 序列化和反序列化对象列表。

在这个问题的帮助下,我整理了一个 POST网络服务。WebService ASP.NET MVC 3 Send and Receive

但是到目前为止,我在根据我的新要求调整该示例方面一直没有成功。

这是我到目前为止从网站 1..

    public static List<ScientificFocusArea> ScientificFocusAreas()
    {
        string apiURL = "http://localhost:50328/Api/GetAPI";

        //Make the post
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        //var bytes = Encoding.Default.GetBytes(body);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
        Stream stream = null;
        try
        {
            request.KeepAlive = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = -1;
            request.Method = "GET";
        }
        finally
        {
            if (stream != null)
            {
                stream.Flush();
                stream.Close();
            }
        }

        List<ScientificFocusArea> listSFA = WebService.GetResponse_ScientificFocusArea(request);

        return listSFA;
    }

    public static List<ScientificFocusArea> GetResponse_ScientificFocusArea(HttpWebRequest request)
    {
        List<ScientificFocusArea> listSFA = new List<ScientificFocusArea>();

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {

            using (Stream responseStream = response.GetResponseStream())
            {
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
                {
                    throw new HttpException((int)response.StatusCode, response.StatusDescription);
                }

                var end = string.Empty;
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    end = reader.ReadToEnd();
                    reader.Close();

                    listSFA = JsonConvert.DeserializeObject<List<ScientificFocusArea>>(end);
                }

                response.Close();
            }
        }

        return listSFA;
    }

然后在网站2...

public class GetAPIController : Controller
{
    //
    // GET: /Api/GetAPI/

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult GetScientificFocusAreas()
    {
        //Get list of SFAs
        List<ScientificFocusArea> ListSFA = CreateList.ScientificFocusArea();

        string json = JsonConvert.SerializeObject(ListSFA, Formatting.Indented);

        //Send the the seralized object.
        return Json(json);

    }

}

另外,在网站 2 上,我已经为传入请求注册了这条路线......

        context.MapRoute(
"GetScientificFocusAreas",
"Api/GetAPI/",
new
{
    controller = "GetAPI",
    action = "GetScientificFocusAreas",
    id = UrlParameter.Optional
}

);

我目前收到错误消息。他的远程服务器返回了一个错误:(404)未找到。

任何帮助我都会非常感激。

4

1 回答 1

0

这个问题似乎是一个路由问题。我将从可以在此处找到的 RouteDebugger 开始。此工具可让您深入了解您的 URL 正在访问哪些路由。

我用于 HTTP GET 的代码与您上面的代码有些不同。它包含在下面。

    public T Get<T>(string url)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            using (Stream responseStream = response.GetResponseStream())
            {
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
                {
                    throw new HttpException((int)response.StatusCode, response.StatusDescription);
                }

                var end = string.Empty;
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    end = reader.ReadToEnd();
                    reader.Close();
                }

                responseStream.Close();
                response.Close();

                JsonSerializer serializer = new JsonSerializer();
                serializer.Binder = new DefaultSerializationBinder();
                JsonReader jsonReader = new JsonTextReader(new StringReader(end));
                T deserialize = serializer.Deserialize<T>(jsonReader);

                return deserialize;
            }

        }
        catch (Exception ex)
        {
            throw new ApiException(string.Format("An error occured while trying to contact the API. URL: {0}", url), ex);
        }
    }

我看到的另一个问题是GetScientificFocusAreas()方法。在代码的第二行,对象被转换为 JSON。这很好,但是 json 的最后一行代码被传递到Json()方法中。这再次将字符串转换为 Json。使用 JSON.Net 库时,使用instead ofContent()中的方法并将内容类型设置为application/jsonreturnJson()

使用外部 Json 转换器而不是内部转换器的原因仅仅是内部 json 转换器存在一些已知问题。JSON.Net 已经存在多年并且很稳固。

于 2012-07-25T16:22:19.687 回答