对控制器的请求不通过ASP.NET Core MVC

w6lpcovy  于 2023-03-31  发布在  .NET
关注(0)|答案(1)|浏览(152)

我刚开始学习MVC。我想也许我不太明白如何添加新的API控制器。我添加了一个新的api控制器使用实体来处理数据库中的一个新表。第一个api控制器工作正常。
第一个控制器返回jsom文件。下面是他的代码:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TestReact.Models;

namespace TestReact.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ChildrenController : ControllerBase
{
private readonly ClinicContext _context;

public ChildrenController(ClinicContext context)
{
_context = context;
}

// GET: api/Children
[HttpGet]
public async Task<ActionResult<IEnumerable<Child>>> GetChildren()
{

var test = _context.Mkb10s.ToList();

return await _context.Children
.ToListAsync();
}

[HttpPut("{id}")]
public async Task<IActionResult> PutChild(int id, Child child)
{
if (id != child.ChildId)
{
return BadRequest();
}

_context.Entry(child).State = EntityState.Modified;

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ChildExists(id))
{
return NotFound();
}
else
{
throw;
}
}

return NoContent();
}

// POST: api/Children
//To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Child>> PostChild(Child child)
{
//Console.WriteLine(child);
_context.Children.Add(child);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ChildExists(child.ChildId))
{
return Conflict();
}
else
{
throw;
}
}

return CreatedAtAction("GetChild", new { id = child.ChildId }, child);
}

// DELETE: api/Children/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteChild(int id)
{
var child = await _context.Children.FindAsync(id);
if (child == null)
{
return NotFound();
}

_context.Children.Remove(child);
await _context.SaveChangesAsync();

return NoContent();
}

private bool ChildExists(int id)
{
return _context.Children.Any(e => e.ChildId == id);
}
}
}

并且是向第二控制器返回的请求:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <base href="/" />
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>TestReact</title>
    <script defer src="/static/js/bundle.js"></script>
</head>

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
</body>

</html>

他的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TestReact.Models;

namespace TestReact.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class Mkb10Controller : ControllerBase
{
private readonly ClinicContext _context;

public Mkb10Controller(ClinicContext context)
{
_context = context;
}

// GET: api/Mkb10
[HttpGet]
public async Task<ActionResult<IEnumerable<Mkb10>>> GetMkb10s()
{
if (_context.Mkb10s == null)
{
return NotFound();
}
return await _context.Mkb10s.ToListAsync();
}

// GET: api/Mkb10/5
[HttpGet("{id}")]
public async Task<ActionResult<Mkb10>> GetMkb10(int id)
{
if (_context.Mkb10s == null)
{
return NotFound();
}
var mkb10 = await _context.Mkb10s.FindAsync(id);

if (mkb10 == null)
{
return NotFound();
}

return mkb10;
}

// PUT: api/Mkb10/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutMkb10(int id, Mkb10 mkb10)
{
if (id != mkb10.Id)
{
return BadRequest();
}

_context.Entry(mkb10).State = EntityState.Modified;

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Mkb10Exists(id))
{
return NotFound();
}
else
{
throw;
}
}

return NoContent();
}

// POST: api/Mkb10
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Mkb10>> PostMkb10(Mkb10 mkb10)
{
if (_context.Mkb10s == null)
{
return Problem("Entity set 'ClinicContext.Mkb10s' is null.");
}
_context.Mkb10s.Add(mkb10);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (Mkb10Exists(mkb10.Id))
{
return Conflict();
}
else
{
throw;
}
}

return CreatedAtAction("GetMkb10", new { id = mkb10.Id }, mkb10);
}

// DELETE: api/Mkb10/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteMkb10(int id)
{
if (_context.Mkb10s == null)
{
return NotFound();
}
var mkb10 = await _context.Mkb10s.FindAsync(id);
if (mkb10 == null)
{
return NotFound();
}

_context.Mkb10s.Remove(mkb10);
await _context.SaveChangesAsync();

return NoContent();
}

private bool Mkb10Exists(int id)
{
return (_context.Mkb10s?.Any(e => e.Id == id)).GetValueOrDefault();
}
}
}

Program.cs代码

using Microsoft.EntityFrameworkCore;
using TestReact.Models;
using TestReact.Controllers;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

string connection = builder.Configuration.GetConnectionString("DefaultConnection");

//builder.Services.AddControllersWithViews();

builder.Services.AddControllers().AddControllersAsServices();

builder.Services.AddDbContext<ClinicContext>(options => options.UseSqlServer(connection));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// 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.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();
tv6aics1

tv6aics11#

@xodiz
首先,根据你的代码,你正在尝试SPA模式而不是MVC模式。如果你想尝试MVC项目,你可以按照这个document
你的控制器都没有返回Html代码(ViewResult),所以我认为你第二次访问一个路径错误的控制器时,它会返回index.html的html代码。因为你调用了app.MapFallbackToFile("index.html");,当注册的路由都不匹配你的路径时,它会返回index.html而不是返回404。
[Route("api/[controller]")]这样的路由属性会覆盖你在program.cs中注册的路由:

app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");

例如,如果您尝试使用/api/Children,您将收到json数据,如果您尝试使用"/Children/GetChildren",您将收到index.html的html代码
您可以检查此document相关路由以了解更多详细信息

相关问题