我正在使用react.js创建一个ASP.NET Core单页应用程序。我在客户内部进行POST时遇到404未找到。我尝试使用postman并传递相应的数据,但没有找到问题。我对此不太有经验,如果我缺少任何东西或者您想查看更多代码,请告诉我。谢谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KCA.Core.Exceptions;
using KCA.Core.Interfaces;
using KCA.Core.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace KCA.WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
private readonly ICustomerServices _customerServices;
public CustomerController(ICustomerServices customerServices)
{
_customerServices = customerServices;
}
// GET: api/Customer
[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
{
try
{
var customers = await _customerServices.GetAllAsync();
return Ok(customers);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// GET: api/Customer/{id}
[HttpGet("{id}")]
public async Task<ActionResult<Customer>> GetCustomer(Guid id)
{
try
{
var customer = await _customerServices.GetByIdAsync(id);
return Ok(customer);
}
catch (NotFoundException ex)
{
return NotFound(ex.Message);
}
catch (BadRequestException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// POST: api/Customer
[HttpPost]
public async Task<ActionResult<Customer>> PostCustomer([FromBody] Customer customer)
{
try
{
await _customerServices.AddAsync(customer);
return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
}
catch (BadRequestException ex)
{
return BadRequest(ex.Message);
}
catch (ConflictException<Customer> ex)
{
return Conflict(ex.Message);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// PUT: api/Customer/{id}
[HttpPut("{id}")]
public async Task<IActionResult> PutCustomer(Guid id, [FromBody] Customer customer)
{
if (id != customer.Id)
{
return BadRequest("Customer ID mismatch.");
}
try
{
await _customerServices.UpdateAsync(customer);
return NoContent();
}
catch (NotFoundException ex)
{
return NotFound(ex.Message);
}
catch (BadRequestException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
// DELETE: api/Customer/{id}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCustomer(Guid id)
{
try
{
await _customerServices.DeleteAsync(id);
return NoContent();
}
catch (NotFoundException ex)
{
return NotFound(ex.Message);
}
catch (BadRequestException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}
这是Program.cs
,因为我知道其中可能存在问题
using KCA.Infrastructure;
using KCA.Core.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using KCA.Infrastructure.Data;
using KCA.Core.Interfaces;
using KCA.Core.Services;
namespace KCA.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
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)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<KCAContext>(options =>
options.UseSqlServer(connectionString));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<Employee>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<KCAContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddApiAuthorization<Employee, KCAContext>();
//Add Services
services.AddScoped<IKCAContext, KCAContext>();
services.AddScoped<ICarService, CarServices>();
services.AddScoped<ICustomerServices, CustomerServices>();
services.AddScoped<IEmployeeServices, EmployeeServices>();
services.AddScoped<IPartsService, PartsService>();
services.AddScoped<IJobServices, JobServices>();
// Add CORS policy
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseCors("AllowAll");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
endpoints.MapFallbackToFile("index.html");
});
}
}
}
我已经尝试使用 Postman 和通过适当的数据,但仍然得到一个404错误
在 Postman
一个二个一个一个
编辑:这是客户模型encase它是我缺少的东西
using KCA.Core.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace KCA.Core.Models
{
public class Customer
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Phone]
public string ContactNumber { get; set; }
[EmailAddress]
public string Email { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
//Relational data
public virtual ICollection<Car> Cars { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
}
4条答案
按热度按时间9ceoxa921#
https://localhost:44401/api/Customer/PostCustomer
这应该是带有POST方法和一个body的url。
2vuwiymt2#
在Program.cs文件中,在services.AddControllersWithViews()之后添加services.AddControllers()
例如:services. AddControllerWithViews();服务。添加控制器();
ndasle7k3#
API控制器只支持属性路由,不支持任何古老的REST,或者删除ApiController属性
所以把路线定好
关于url
xoefb8l84#
您可以尝试发布到http://localhost:44401/api/Customer/PostCustomer URL。问题可能是https。