MVC 3获取Web服务和响应

时间:2012-07-24 17:32:00

标签: asp.net-mvc-3 json.net

我正在尝试构建一个GET Web服务,该服务将从网站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)Not Found。

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

1 个答案:

答案 0 :(得分:0)

问题似乎是路由问题。我将从RouteDebugger开始,可以找到here。此工具可让您深入了解网址所针对的路线。

我用于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库时,使用Content()中的return方法而不是Json(),并将内容类型设置为 application / json

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