Главная индексная страница содержит ссылку для тестирования API:
Код: Выделить всё
[[email protected](]ApiTester Click Here[/url]
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using TestWebApplication.Models;
namespace TestWebApplication.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public async Task ApiTester()
{
var client = new HttpClient();
var values = new Dictionary { { "Name", "Alice" } };
var content = new FormUrlEncodedContent(values);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await client.PostAsync("https://localhost:7284/api/Auth/ApiTest", content);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
ViewBag.ApiResponse = result;
}
else
{
ViewBag.ApiResponse = "Error: " + response.StatusCode;
}
return View();
}
}
}
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace TestWebApplication.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpGet("GetTest")]
public IActionResult GetTest()
{
return Ok(new { message = "Get Test Succesfull!" });
}
[HttpPost("ApiTest")]
public IActionResult ApiTest([FromBody] Dictionary values)
{
string name = values["name"];
return Ok(new { message = "200: Post Test Succesfull!" });
}
}
}
Код: Выделить всё
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Код: Выделить всё
public IActionResult ApiTest()
.
.
Подробнее здесь: https://stackoverflow.com/questions/790 ... rp-asp-net