无法运行URL Shortener,当我运行时出现错误

问题描述 投票:1回答:1

我是MVC的新手。我在运行时遇到异常时,在ASP.NET MVC中创建了URL缩短器服务,但运行时却出现异常,而我却遇到错误。我正在使用Google URL Shortener API。我在哪里错过任何一步?

我在以下位置遇到问题:

var resp = req.GetResponse();

代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Web.Script.Serialization;
    using UrlShortner.Models;

    namespace UrlShortner.Controllers
    {
        public class HomeController : Controller
        {

            // Enter your Google URL Shortener API key here
            const string API_KEY = "AIzaSyBYOT4rQDtTasdadFJmz3yzmfmnwYQqHsd";
            public ActionResult Index()
            {
                return View();
            }

            [HttpPost]
            public ActionResult Index(FormCollection form)
            {
                string longUrl = Convert.ToString(form["longUrl"]);
                var shortenedResponse = Shorten(longUrl);

                ViewBag.ShortenedUrl = shortenedResponse.id;
                return View();
            }

            public static ShortenLongUrlResponse Shorten(string longUrl)
            {
                if (string.IsNullOrWhiteSpace(longUrl))
                    throw new ArgumentException("You must provide a value for longUrl");

                var req = WebRequest.Create(GetUrl());
                req.Method = "POST";
                req.ContentType = "application/json";

                var postBody = string.Format(@"{{""longUrl"": ""{0}""}}", longUrl);
                var postData = Encoding.ASCII.GetBytes(postBody);

                req.ContentLength = postData.Length;
                var reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();


                var resp = req.GetResponse();
                using (var respReader = new StreamReader(resp.GetResponseStream()))
                {
                    var responseBody = respReader.ReadToEnd();

                    var deserializer = new JavaScriptSerializer();
                    return deserializer.Deserialize<ShortenLongUrlResponse>(responseBody);
                }
            }

            protected static string GetUrl()
            {
                const string API_URL = "https://www.googleapis.com/urlshortener/v1/url";

                if (string.IsNullOrWhiteSpace(API_KEY))
                    return API_URL;
                else
                    return string.Concat(API_URL, "?key=", API_KEY);
            }

        }
    }
asp.net-mvc asp.net-web-api model-view-controller url-shortener google-url-shortener
1个回答
0
投票

根据Google的规定,截至2019年3月30日,goo.gl URL缩短程序已关闭。请参阅此博客文章以了解替代方法。

您必须从Google阅读此博客。https://developers.googleblog.com/2018/03/transitioning-google-url-shortener.html

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.