PUT, DELETE Not Working (error 404) for ASP.NET core Web API Templates - asp.net-core

I have tried several modifications even in .config file to enable those verbs but nothing works.
GET method works fine but 404 for PUT and DELETE.
I already tried removing WebDav Module and other IIS related modifications.
Here is my Controller :
[HttpPut("{id:length(24)}")]
public IActionResult Update(string id, Client clientIn)
{
var client = _clientService.Get(id);
if (client == null)
{
return NotFound();
}
_clientService.Update(id, clientIn);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
[Route("api/Clients/{id}")]
public IActionResult Delete(string id)
{
var client = _clientService.Get(id);
if (client == null)
{
return NotFound();
}
_clientService.Remove(client.ClientId);
return NoContent();
}

I do not know how you set the HttpGet. In this code, because you limit the length of the id, the id must be up to 24 characters to be mapped. You can change it like this.
[HttpPut("{id:maxlength(24)}")]
public IActionResult Update(string id, Client clientIn)
{
//
}
And you can refer to this route constraints.

Related

How to use fallback routing in asp.net core?

I am using asp.net web-api with controllers.
I want to do a user section where one can request the site's address with the username after it like example.com/username. The other, registered routes like about, support, etc. should have a higher priority, so if you enter example.com/about, the about page should go first and if no such about page exists, it checks whether a user with such name exists. I only have found a way for SPA fallback routing, however I do not use a SPA. Got it working manually in a middleware, however it is very complicated to change it.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
string[] internalRoutes = new string[] { "", "about", "support", "support/new-request", "login", "register" };
string[] userNames = new string[] { "username1", "username2", "username3" };
app.Use(async (context, next) =>
{
string path = context.Request.Path.ToString();
path = path.Remove(0, 1);
path = path.EndsWith("/") ? path[0..^1] : path;
foreach (string route in internalRoutes)
{
if (route == path)
{
await context.Response.WriteAsync($"Requested internal page '{path}'.");
return;
}
}
foreach (string userName in userNames)
{
if (userName == path)
{
await context.Response.WriteAsync($"Requested user profile '{path}'.");
return;
}
}
await context.Response.WriteAsync($"Requested unknown page '{path}'.");
return;
await next(context);
});
app.Run();
It's really straightforward with controllers and attribute routing.
First, add controller support with app.MapControllers(); (before app.Run()).
Then, declare your controller(s) with the appropriate routing. For simplicity, I added a single one that just returns simple strings.
public class MyController : ControllerBase
{
[HttpGet("/about")]
public IActionResult About()
{
return Ok("About");
}
[HttpGet("/support")]
public IActionResult Support()
{
return Ok("Support");
}
[HttpGet("/support/new-request")]
public IActionResult SupportNewRequest()
{
return Ok("New request support");
}
[HttpGet("/{username}")]
public IActionResult About([FromRoute] string username)
{
return Ok($"Hello, {username}");
}
}
The routing table will first check if there's an exact match (e.g. for /about or /support), and if not, if will try to find a route with matching parameters (e.g. /Métoule will match the /{username} route).

ASP.NET Core WEB API Problem with GET parameters in API method

I have this controller
[ApiController]
[Route("api/[controller]")]
public class FamiliesController : ControllerBase
{
readonly FamilyFinanceContext db;
public FamiliesController(FamilyFinanceContext context)
{
db = context;
}
[HttpDelete("deletefamily")]
public async Task<ActionResult<Family>> DeleteFamilly(int id)
{
Family user = db.Families.FirstOrDefault(x => x.Id == id);
if (user == null)
{
return NotFound();
}
db.Families.Remove(user);
await db.SaveChangesAsync();
return Ok(user);
}
}
after call https://localhost:44373/api/families/deletefamily?id=2 i have this error - HTTP ERROR 405
In theory this GET parameters must work. What i done not correctly?
As ESG stated, your trying to do a DELETE, so you need to use the DELETE verb, not the GET verb. You're getting a 405 Method Not Allowed for this reason (you cannot use GET on a DELETE action). You should use a tool like PostMan (https://www.postman.com/) to create your DELETE requests, since you can't really do it easily just in a browser.
To fall more in line with REST convention, you should consider changing your DELETE method slightly:
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteFamily([FromRoute] int id)
{
Family user = db.Families.FirstOrDefault(x => x.Id == id);
if (user == null)
{
return NotFound();
}
db.Families.Remove(user);
await db.SaveChangesAsync();
return NoContent();
}
You would then call this as DELETE https://localhost:44373/api/families/2
By using the [HttpDelete("{id}"] attribute, your moving the id from the query string to the URI, which is more in line with REST convention (the URI represents an object). Query string parameters are more typically used for optional capabilities, such as filtering, sorting, etc and not the endpoint representing the object itself.
Typically DELETE actions do not return content, but that is up to you. If you really want to return the user object, then stick with Ok(user), but NoContent is more typical of the DELETE verb.

swagger : Failed to load API definition undefined /swagger/v1/swagger.json

I have tried to configure swagger in my asp.net core api and getting the following error. Failed to load API definition undefined /swagger/v1/swagger.json
I am not sure why I am getting this error. I have added the necessary configuration in the startup file
I have tried the following paths but there has been no difference
/swagger/v1/swagger.json
../swagger/v1/swagger.json
v1/swagger.json
startup.cs
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>
{
});
services.AddDbContext<NorthwindContext>(item => item.UseSqlServer(Configuration.GetConnectionString("NorthwindDBConnection")));
services.AddCors(option => option.AddPolicy("MyPolicy", builder => {
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
}));
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddScoped<ICustomerRepository, CustomerRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseCors("MyPolicy");
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API name"); });
app.UseMvc();
}
}
CustomerController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Customer.Repository;
using CustomerService.Models;
using CustomerService.ViewModel;
using Microsoft.AspNetCore.Mvc;
namespace CustomerService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomersController : Controller
{
ICustomerRepository _customersRepository;
public CustomersController(ICustomerRepository customersRepository)
{
_customersRepository = customersRepository;
}
[HttpGet]
[Route("GetCustomers")]
//[NoCache]
[ProducesResponseType(typeof(List<CustomerViewModel>), 200)]
[ProducesResponseType(typeof(ApiResponse), 400)]
public async Task<IActionResult> Customers()
{
try
{
var customers = await _customersRepository.GetAllCustomers();
if (customers == null)
{
return NotFound();
}
return Ok(customers);
}
catch
{
return BadRequest();
}
}
[HttpGet]
[Route("GetCustomer")]
//[NoCache]
[ProducesResponseType(typeof(List<CustomerViewModel>), 200)]
[ProducesResponseType(typeof(ApiResponse), 400)]
public async Task<IActionResult> Customers(string customerId)
{
if (customerId == null)
{
return BadRequest();
}
try
{
var customer = await _customersRepository.GetCustomer(customerId);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
catch
{
return BadRequest();
}
}
[HttpPost]
[Route("AddCustomer")]
public async Task<IActionResult> AddCustomer([FromBody] CustomerViewModel model)
{
if (ModelState.IsValid)
{
try
{
var customerId = await _customersRepository.Add(model);
if (customerId != null)
{
return Ok(customerId);
}
else
{
return NotFound();
}
}
catch(Exception ex)
{
return BadRequest();
}
}
return BadRequest();
}
[HttpPost]
[Route("DeleteCustomer")]
public async Task<IActionResult> DeleteCustomer(string customerId)
{
int result = 0;
if (customerId == null)
{
return BadRequest();
}
try
{
var customer = await _customersRepository.Delete(customerId);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
catch
{
return BadRequest();
}
}
[HttpPost]
[Route("UpdateCustomer")]
public async Task<IActionResult> UpdateCustomer([FromBody] CustomerViewModel model)
{
if (ModelState.IsValid)
{
try
{
await _customersRepository.Update(model);
return Ok();
}
catch(Exception ex)
{
if (ex.GetType().FullName == "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException")
{
return NotFound();
}
return BadRequest();
}
}
return BadRequest();
}
}
}
Swagger also cannot deal with two Classes having the same name (at least, not out of the box). So if you have two name spaces, and two classes having the same name, it will fail to initialize.
If you are on the broken Swashbuckle page, Open Dev Tools ... look at the 500 response that Swagger sends back and you will get some great insight.
Here's the dumb thing I was doing ... had a route in the HTTPGet as well as a ROUTE route.
[HttpGet("id")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(500)]
[Route("{employeeID:int}")]
You are getting an error. Because of you doubled your action names. Look at this example.
Swagger – Failed To Load API Definition , Change [Route("GetCustomers")] names and try again.
I know this was is resolved, but I had this same problem today.
In my case, the problem was that I had a base controller class I created to other controllers inherit from.
The problem started to happen when I created a public function on the base class. Turning it to protected did the trick
This is usually indicative of controllers/actions that Swashbuckle doesn't support for one reason or another.
It's expected that you don't have a swagger.json file in your project. Swashbuckle creates and serves that dynamically using ASP.NET Core's ApiExplorer APIs. What's probably happening here is that Swashbuckle is unable to generate Swagger.json and, therefore, the UI is failing to display.
It's hard to know exactly what caused the failure, so the best way to debug is probably just to remove half your controllers (just move the files to a temporary location) and check whether the issues persists. Then you'll know which half of your controllers contains the troublesome action. You can 'binary search' removing controllers (and then actions) until you figure out which action method is causing Swashbuckle to not be able to generate Swagger.json. Once you know that, it should be obvious whether this is some issue in your code or an issue that should be filed in the Swashbuckle repo.
You could press F12 to open the chrome browser's developer tools to check the cause of failure ,then enter the failed request path and click on the error file to preview the detailed error .
It could also be an issue with ambiguous routes or something like that tripping Swashbuckle up. Once you've narrowed down the cause of failure to something more specific like that, it can either be fixed or filed, as appropriate.
If you want to access swagger via host:port/swagger/v1/swagger.json then you should add options: SwaggerGenOptions inside
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
c.SwaggerDoc("swagger/v1", new OpenApiInfo { Version = "1.0", Title = "API" });
);
}
It should work properly.

Multiple Access Denied Pages

I'm creating an application that has two different authorization scenarios: admin and site.
If you try to access a /admin route without the policy succeeding the user should be redirected to an access denied page. At this point there's no action the user can take. They can't access the resource and there's nothing for them to do.
If you try to access a /site/joes-super-awesome-site route without the policy suceeding the user should be redirected to a different access denied. At this point the user should be able to request access. There is an action they can take.
What's the best way to achieve this? I know I can override the default OnRedirectToAccessDenied action but that will require some ugly string parsing (untested example below).
.AddCookie(options => {
options.Events.OnRedirectToAccessDenied = context => {
// parsing this kinda sucks.
var pathParts = context.Request.Path.Value.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (pathParts?[0] == "site") {
context.Response.Redirect($"/{pathParts[0]}/request-access");
} else {
context.Response.Redirect("/account/access-denied");
}
return Task.CompletedTask;
};
})
Doing some searching, I found the following information:
Someone with the same question on this GitHub issue
Tracking of authorization-related improvements in this GitHub issue
Unfortunately these improvements didn't make it to ASP.NET Core 2.1.
It seems that at this point, another option (apart from your suggestion of parsing the request URL) is to imperatively invoke the authorization service in your MVC actions.
It could go from:
// Highly imaginary current implementation
public class ImaginaryController : Controller
{
[HttpGet("site/{siteName}")]
[Authorize("SitePolicy")]
public IActionResult Site(string siteName)
{
return View();
}
[HttpGet("admin")]
[Authorize("AdminPolicy")]
public IActionResult Admin()
{
return View();
}
}
to:
public class ImaginaryController : Controller
{
private readonly IAuthorizationService _authorization;
public ImaginaryController(IAuthorizationService authorization)
{
_authorization = authorization;
}
[HttpGet("site/{siteName}")]
public Task<IActionResult> Site(string siteName)
{
var sitePolicyAuthorizationResult = await _authorization.AuthorizeAsync(User, "SitePolicy");
if (!sitePolicyAuthorizationResult.Success)
{
return Redirect($"/site/{siteName}/request-access");
}
return View();
}
[HttpGet("admin")]
public Task<IActionResult> Admin()
{
var adminPolicyAuthorizationResult = await _authorization.AuthorizeAsync(User, "AdminPolicy");
if (!adminPolicyAuthorizationResult.Success)
{
return Redirect("/account/access-denied");
}
return View();
}
}

Post web method not firing + asp.net core webapi

I am implementing CRUD operations using EF7 and storedprocudures in asp.net core web api project. I have finished implementing the get methods and left with the insert method. I am using Postman to test the web methods. I have written the implementation for Create but unable the post the information via postman isn't hitting the Create web method in the controller. Could somebody let me know what the problem could be. The route of the get and post is the same except the method signature is different.
Controller
public class MoviesController : Controller
{
private readonly IMoviesRepository _moviesRepository;
public MoviesController(IMoviesRepository moviesRepository)
{
_moviesRepository = moviesRepository;
}
[HttpGet]
[Route("api/Movies")]
public async Task<IActionResult> GetMovies()
{
var movies = await _moviesRepository.GetMovies();
var results = Mapper.Map<IEnumerable<MoviesDto>>(movies);
return Ok(results);
}
[HttpGet]
[Route("api/Movies/{ID}")]
public async Task<IActionResult> GetMovie(int ID)
{
var movie = await _moviesRepository.GetMovie(ID);
var results = Mapper.Map<IEnumerable<MoviesDto>>(movie);
return Ok(results);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("api/Movies")]
public IActionResult CreateMovie([FromBody] MoviesDto movies)
{
if (movies == null)
{
return BadRequest();
}
// Check if movie exists
var movie = _moviesRepository.GetMovie(movies.MovieId);
if (movie == null)
{
return NotFound();
}
var results = Mapper.Map<Movies>(movies);
if (ModelState.IsValid)
{
_moviesRepository.AddMovie(results);
}
return Ok(results);
}
}
Postman
This issue has been fixed. I had to remove the anti-forgery token