为什么我不能在我为 vk bot 制作的 razor-pages 网站上 post json
Why can`t i post json on my razor-pages web site i made for vk bot
当我尝试 post JSON https://centroban.herokuapp.com/api/callback 上的数据时出现 404 错误。它写在 c# 和 razor 页面上。你能帮帮我吗
这是Callback.cs文件
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using VkNet.Abstractions;
using VkNet.Model;
using VkNet.Model.RequestParams;
using VkNet.Utils;
namespace Centroban
{
[Route("api/[controller]")]
[ApiController]
public class CallbackController : ControllerBase
{
/// <summary>
/// Конфигурация приложения
/// </summary>
/// private readonly IConfiguration _configuration;
private readonly IVkApi _vkApi;
private readonly IConfiguration _configuration;
public CallbackController(IVkApi vkApi, IConfiguration configuration)
{
_vkApi = vkApi;
_configuration = configuration;
}
[HttpPost]
public IActionResult Callback([FromBody] Updates updates)
{
// Проверяем, что находится в поле "type"
switch (updates.Type)
{
// Если это уведомление для подтверждения адреса
case "confirmation":
// Отправляем строку для подтверждения
return Ok(_configuration["Config:Confirmation"]);
case "message_new":
{
// Десериализация
var msg = Message.FromJson(new VkResponse(updates.Object));
// Отправим в ответ полученный от пользователя текст
_vkApi.Messages.Send(new MessagesSendParams
{
RandomId = new DateTime().Millisecond,
PeerId = msg.PeerId.Value,
Message = msg.Text
});
break;
}
}
// Возвращаем "ok" серверу Callback API
return Ok("ok");
}
}
}
这是Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using VkNet;
using VkNet.Abstractions;
using VkNet.Model;
namespace Centroban
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddControllers();
services.AddSingleton<IVkApi>(sp =>
{
var api = new VkApi();
api.Authorize(new ApiAuthParams { AccessToken = Configuration["Config:AccessToken"] });
return api;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
我猜路由有问题,但无论如何,我不知道如何处理它们。
这是我的网站 https://centroban.herokuapp.com
首先,你可以尝试为mvc添加路由:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
然后你不能使用
https://centroban.herokuapp.com/api/callback
在浏览器中调用动作,因为它是一个 HttpPost
request.Here 是在邮递员中调用动作的示例。
当我尝试 post JSON https://centroban.herokuapp.com/api/callback 上的数据时出现 404 错误。它写在 c# 和 razor 页面上。你能帮帮我吗
这是Callback.cs文件
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using VkNet.Abstractions;
using VkNet.Model;
using VkNet.Model.RequestParams;
using VkNet.Utils;
namespace Centroban
{
[Route("api/[controller]")]
[ApiController]
public class CallbackController : ControllerBase
{
/// <summary>
/// Конфигурация приложения
/// </summary>
/// private readonly IConfiguration _configuration;
private readonly IVkApi _vkApi;
private readonly IConfiguration _configuration;
public CallbackController(IVkApi vkApi, IConfiguration configuration)
{
_vkApi = vkApi;
_configuration = configuration;
}
[HttpPost]
public IActionResult Callback([FromBody] Updates updates)
{
// Проверяем, что находится в поле "type"
switch (updates.Type)
{
// Если это уведомление для подтверждения адреса
case "confirmation":
// Отправляем строку для подтверждения
return Ok(_configuration["Config:Confirmation"]);
case "message_new":
{
// Десериализация
var msg = Message.FromJson(new VkResponse(updates.Object));
// Отправим в ответ полученный от пользователя текст
_vkApi.Messages.Send(new MessagesSendParams
{
RandomId = new DateTime().Millisecond,
PeerId = msg.PeerId.Value,
Message = msg.Text
});
break;
}
}
// Возвращаем "ok" серверу Callback API
return Ok("ok");
}
}
}
这是Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using VkNet;
using VkNet.Abstractions;
using VkNet.Model;
namespace Centroban
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddControllers();
services.AddSingleton<IVkApi>(sp =>
{
var api = new VkApi();
api.Authorize(new ApiAuthParams { AccessToken = Configuration["Config:AccessToken"] });
return api;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
我猜路由有问题,但无论如何,我不知道如何处理它们。 这是我的网站 https://centroban.herokuapp.com
首先,你可以尝试为mvc添加路由:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
然后你不能使用
https://centroban.herokuapp.com/api/callback
在浏览器中调用动作,因为它是一个 HttpPost
request.Here 是在邮递员中调用动作的示例。