C
C#4mo ago
Mastalt

MVC App's Post request not reaching

First off, yes I already asked this last friday but couldn't follow trough due to not having the source code for the weekend. Either way, here's my problem: I have an MVC Web Api in .NET 8.0, all Get requests from all controllers work as intended, but for Post requests on the other hand, they all return an HTTP Error 405 (Method not Allowed). Here is my initialization class and one of my Post method (they are all basiaclly structured the same) (Also, all the Cors stuff are things I already tried with no avail) Initialization Class:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<SkyblockRessourcesAPIContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SkyblockRessourcesAPIContext") ?? throw new InvalidOperationException("Connection string 'SkyblockRessourcesAPIContext' not found."), x => x.UseNetTopologySuite()));

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddCors(o => o.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
}));

var app = builder.Build();

app.UseCors(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});

// 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();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<SkyblockRessourcesAPIContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SkyblockRessourcesAPIContext") ?? throw new InvalidOperationException("Connection string 'SkyblockRessourcesAPIContext' not found."), x => x.UseNetTopologySuite()));

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddCors(o => o.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
}));

var app = builder.Build();

app.UseCors(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});

// 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();
Controller Example:
[Route("api/[controller]")]
[ApiController]
public class RegionsController : ControllerBase
{
private readonly SkyblockRessourcesAPIContext _context;

public RegionsController(SkyblockRessourcesAPIContext context)
{
_context = context;
}

// GET: api/Regions/Get
[HttpGet]
[Route("Get")]
public async Task<ActionResult<IEnumerable<Region>>> GetRegion()
{
return await _context.Region.ToListAsync();
}

// POST: api/Regions/Post
[EnableCors("*", "*", "*")]
[HttpPost]
[Route("Post")]
public async Task<ActionResult<Region>> PostRegion([FromBody] Region region)
{
_context.Region.Add(region);
await _context.SaveChangesAsync();

return CreatedAtAction("GetRegion", new { id = region.Id }, region);
}

// DELETE: api/Regions/Delete
[HttpDelete]
[Route("Delete/all")]
public async Task<IActionResult> DeleteAllRegion()
{
var region = await _context.Region.ToListAsync();
if (region == null)
{
return NotFound();
}

_context.Region.RemoveRange(region);

return NoContent();
}

// DELETE: api/Regions/Delete?id=5
[HttpDelete]
[Route("Delete")]
public async Task<IActionResult> DeleteRegion(int id)
{
var region = await _context.Region.FindAsync(id);
if (region == null)
{
return NotFound();
}

_context.Region.Remove(region);
await _context.SaveChangesAsync();

return NoContent();
}
[Route("api/[controller]")]
[ApiController]
public class RegionsController : ControllerBase
{
private readonly SkyblockRessourcesAPIContext _context;

public RegionsController(SkyblockRessourcesAPIContext context)
{
_context = context;
}

// GET: api/Regions/Get
[HttpGet]
[Route("Get")]
public async Task<ActionResult<IEnumerable<Region>>> GetRegion()
{
return await _context.Region.ToListAsync();
}

// POST: api/Regions/Post
[EnableCors("*", "*", "*")]
[HttpPost]
[Route("Post")]
public async Task<ActionResult<Region>> PostRegion([FromBody] Region region)
{
_context.Region.Add(region);
await _context.SaveChangesAsync();

return CreatedAtAction("GetRegion", new { id = region.Id }, region);
}

// DELETE: api/Regions/Delete
[HttpDelete]
[Route("Delete/all")]
public async Task<IActionResult> DeleteAllRegion()
{
var region = await _context.Region.ToListAsync();
if (region == null)
{
return NotFound();
}

_context.Region.RemoveRange(region);

return NoContent();
}

// DELETE: api/Regions/Delete?id=5
[HttpDelete]
[Route("Delete")]
public async Task<IActionResult> DeleteRegion(int id)
{
var region = await _context.Region.FindAsync(id);
if (region == null)
{
return NotFound();
}

_context.Region.Remove(region);
await _context.SaveChangesAsync();

return NoContent();
}
6 Replies
Angius
Angius4mo ago
You mean a POST: /api/Regions/Post request results in 405? I wonder if the issue might be with that CreatedAtAction...? You pass an object with an id to it, yet the GetRegion method neither takes nor returns it As a side note,
[HttpWhatever]
[Route("some/route")]
[HttpWhatever]
[Route("some/route")]
can just be
[HttpWhatever("some/route")]
[HttpWhatever("some/route")]
Mastalt
Mastalt4mo ago
Yes I changed that and that resolved the error 405, but now I have some other problems: I am getting an error 415 if i use [FromBody], but [FromForm] returns an error 400, problem is I have no clue how to make a post request with [FromForm]
Angius
Angius4mo ago
What's 415 remind me?
Mastalt
Mastalt4mo ago
Unsupported Media Type
string jsonData = JsonConvert.SerializeObject(r, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
HttpResponseMessage response = await _client.PostAsync("https://localhost:7145/api/Regions/Post", new StringContent(jsonData, Encoding.UTF8, "application/json"));
string jsonData = JsonConvert.SerializeObject(r, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
HttpResponseMessage response = await _client.PostAsync("https://localhost:7145/api/Regions/Post", new StringContent(jsonData, Encoding.UTF8, "application/json"));
This is my request Actually, it doesn't seem to be reaching at all, I have a breakpoint in my API and it is never hit, but when I try to reach the call straight from my browser, then it return 415 (which I'm guessing is normal since I don't send any body when trying this way) Update: Whatever I did (I just reverted to my old code) now works, only problem is that I need to desrialize NetTopologySuite json to object in MVC.
Angius
Angius4mo ago
Any particular reason for this whole song and dance instead of just
var response = await _client.PostAsJsonAsync(url, r);
var response = await _client.PostAsJsonAsync(url, r);
? Far as unsupported media type, it happens when you bind from body but send a form, or bind from form but send JSON Or any other pair of incompatible media types
Mastalt
Mastalt4mo ago
Tbh, I totally forgot that was a thing...
Want results from more Discord servers?
Add your server
More Posts