我目前正在尝试将Google Indexing API
客户的服务与他们的ASP.NET Web API
项目(.NET Framework 4.5.2
)集成。我创建了一个控制器,它接受一个 URL 作为输入,然后调用一个自定义服务来尝试将此 URL 发送到Google Indexing API
. 控制器逻辑如下:
namespace GoogleServiceAPI.Controllers
{
public class GoogleController : ApiController
{
private GoogleIndexService googleIndexService;
public GoogleController()
{
googleIndexService = new GoogleIndexService();
}
[OverrideAuthentication]
[OverrideAuthorization]
[Route("SendUrlToGoogle")]
[HttpPost]
public HttpResponseMessage SendUrlToGoogle(string url)
{
try
{
var response = PostUrlToGoogle(url, GoogleIndexAction.URL_UPDATED).GetAwaiter().GetResult();
var message = response.Content.ReadAsStringAsync().Result;
return Request.CreateResponse(HttpStatusCode.OK, message);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
private async Task<HttpResponseMessage> PostUrlToGoogle(string url, GoogleIndexAction action)
{
var response = await googleIndexService.PostUrlToGoogle(url, action);
return response;
}
}
}
自定义服务类代码如下:
namespace GoogleService.Services.Google
{
public class GoogleIndexService : IGoogleIndexService
{
private GoogleCredential googleCredential;
private readonly string googleAPIUrl;
public GoogleIndexService()
{
googleAPIUrl = "https://indexing.googleapis.com/v3/urlNotifications:publish";
}
private GoogleCredential GetGoogleCredential()
{
var path = @"C:\Json\olasjobs-org-indexingapi-7b3cf0fa1e20.json";
GoogleCredential credential;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(new[] { "https://www.googleapis.com/auth/indexing" });
}
return credential;
}
public async Task<HttpResponseMessage> PostUrlToGoogle(string Url, GoogleIndexAction action)
{
googleCredential = GetGoogleCredential();
var serviceAccountCredential = (ServiceAccountCredential)googleCredential.UnderlyingCredential;
var gAction = action.ToString();
var requestBody = new
{
url = Url,
type = gAction
};
var httpClientHandler = new HttpClientHandler();
var cMessageHandler = new ConfigurableMessageHandler(httpClientHandler);
var configurableHttpClient = new ConfigurableHttpClient(cMessageHandler);
serviceAccountCredential.Initialize(configurableHttpClient);
HttpContent content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
var response = await configurableHttpClient.PostAsync(new Uri(googleAPIUrl), content);
return response;
}
}
}
服务接口如下:
namespace GoogleService.Services.Google
{
public interface IGoogleIndexService
{
Task<HttpResponseMessage> PostUrlToGoogle(string Url, GoogleIndexAction action);
}
public enum GoogleIndexAction
{
URL_UPDATED,
URL_DELETED
}
}
我正在测试ASP.NET Web API
通过Postman
,请求只是一直在旋转并且什么都不做。我也有一个console project
我使用与上面相同的服务代码,当我运行它时,请求成功并且 URL 被注册到谷歌。但是我无法通过 Web API 项目获得相同的结果。没有错误,我只是在 Postman 中看到“发送响应”,之后什么也没有发生。我已经验证没有网络问题,因为通过控制台项目一切正常。我在 Web API 项目中做错了吗?有人可以帮帮我吗。我尝试使用硬编码的 URL 和操作值发送请求,但仍然无法正常工作。
谢谢