Having some issues getting started in C#, here's the error I'm getting:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
New to this language, any tips appreciated.
Here's my code:
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Http5112Assignment2.Controllers
{
public class DiceGameController : ApiController
{
[Route("api/J2/DiceGame/{die1}/{die2})")]
public class J2Controller : ApiController
{
[HttpGet]
public int DiceGame(int die1, int die2)
{
int dieSum = die1 + die2;
return dieSum;
}
}
}
}
Kindly do the following.
Move each class to a separate file with the name as the Api controller. In here we can see that you have nested two Api controllers which should not be done.
Api controller route annotations usually looks like [Route("[controller]")] or [Route("api/[controller]")]. Below is an example.
[Route("api/[controller]")]
public class J2Controller : ApiController
{
[HttpGet("DiceGame/{die1}/{die2}")]
public int DiceGame([FromRoute] int die1, [FromRoute] int die2)
{
int dieSum = die1 + die2;
return dieSum;
}
}
If you want to call the DiceGame endpoint, then make sure your Api is running and you can simply do a HTTP GET request to the URL: https://localhost:[yourport]/api/j2/dicegame/69/420.
For more info on routing, visit the following URL.
Create web APIs with ASP.NET Core
I see that there may be a typo in your route string, note the ) in the /{die2})
So, Assuming that you didn't change anything in the default routing in your RouteConfig file, then Make sure you're URL is as follows (note that mine runs on https://localhost:44301 yours may differ)
https://localhost:44301/api/J2/DiceGame/12/34)
Note: It'd be helpful if you provide the request URL you were attempting to use that gave you the error or even better a cURL which is a standard format for that request that gave you the 404
Related
EDIT: If I create an empty ASP.NET CORE WEB APP MVC, I can make it working. I am having problem when I am using MVC with Angular. There might be a problem with SPA proxy as well.
EDIT 2: I found a report https://github.com/dotnet/aspnetcore/issues/38354
I am still trying but no chance.
I can not access my public methods in controller classes. This is my controller:
[Route("authentication")]
public class AuthenticationController : Controller
{
[HttpGet("example")]
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}
And also I tried this attribute as well:
[Route("[controller]")]
public class AuthenticationController : Controller
when I try to navigate to localhost:PORT/authentication/example I am getting 404. I am not using API. I am trying to build a web application with .net core MVC and angular. So I will be just sending GET or POST requests to controllers.
This is my program.cs file
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.Run();
I strongly believe that something is wrong in my program.cs. But I couldn't figure it out.
FIX:
After trying out a few days, I finally found the answer. I had to add my new route into 'proxy' variable in proxy.conf.js file.
const PROXY_CONFIG = [
{
context: [
"/weatherforecast",
"/authentication"
],
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}}
]
you can try this for example, it will work for localhost:PORT/authentication/example
[Route("[controller]/[action]")]
public class AuthenticationController : Controller
{
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}
//or
public class AuthenticationController : Controller
{
[HttpGet("~/Authentication/Example")]
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}
but since you are using a Controller as a base class, not an ApiController for example, everything should be working even if you remove all attribute routing at all.
You need to decorate your controller with method / routing attributes
Try:
[Route("api/[controller]")]
public class AuthenticationController : Controller
{
[HttpGet("example")]
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}
This will create a get endpoint which can be called at api/authentication/example
Returning a 200 status with the text in the body.
The convention is that if Your memers start with an action verb, it can find out automatically, like
public string GetExample()
However you do not want to return raw string, you always want to return an action result, because you want wrapping with explicit HttpStatus response codes, so
public IActionResult<string> GetExample()
Now many of us a bias towards the works by magic because of prefix and like to be more explicit, not only because the attribute notation allows more control, but also for consistency. Because nearly almost always, at least one action method of the controller actually requires that fine grain.
[HttpGet("example")]
public IActionResult<string> Example()
Then often for instance there is an id and you can go
[HttpGet("example/id?")]
public IActionResult<string> Example([FromRoute] string id)
if you want to not have it go through all the places it might be getting your variables from for instance, there are many choices available
I'm building an ASP.NET Core 5.0 Web API application as I mentioned in the title I have an issue when trying to delete a record from the database; I'm getting an error 405 Method Not Allowed response from HttpDelete request.
PS: I have added services.AddCors() and app.UseCors() with default policy.
This is the delete method code
public bool deleteLivreById(int id)
{
Livre l = _db.Livres.Find(id);
_db.Livres.Remove(l);
_db.SaveChanges();
return true;
}
And this is the HttpDelete method inside the controller
[HttpDelete("{id}/delete")]
public bool deleteLivreById(int id)
{
return _objGererLivre.deleteLivreById(id);
}
Finally this is a picture from console when navigating to HttpDelete Url
Edit: This is full code of my controller
namespace GestionLivre.Controllers
{
[ApiController]
[Route("test")]
public class LivreController : Controller
{
private IGererLivre _objGererLivre;
public LivreController(IGererLivre gererLivre)
{
_objGererLivre = gererLivre;
}
[HttpGet]
public JsonResult getLivres()
{
return Json(_objGererLivre.getLivres());
}
[HttpDelete("{id}/delete")]
public bool deleteLivreById(int id)
{
return _objGererLivre.deleteLivreById(id);
}
}
}
I opened the screenshot and noticed that you have selected 'GET' as http verb and method type is 'Delete'. Could you please change that and try.
As I understand by default when you're trying to access URL in browser it uses GET method. So we should to pass in header appropriate method(POST,GET,DELETE,PATCH,PUT) If you want to test HTTP methods I'll recommend you to use Postman or Swagger. Postman much easier to use whether than Swagger which you should to add to service configuration and middleware.
Example of Postman:
And than configure body like that to return response.
Also recommend you to use REST Best Practices. And name resources properly. https://restfulapi.net/resource-naming/#:~:text=2.-,Best%20Practices,-2.1.%20Use%20nouns
need help related to Swagger Controller in DotnetCore C#
Here is the controller config for Swagger.
[ApiVersion("1")]
[Route("/DCSapi/v{version:apiVersion}/[controller]")]
[ApiController]
public class DCSSampleController : ControllerBase
{
private readonly string _version = "v1";
[HttpGet]
[Route("/DCSapi/v{version:apiVersion}/[controller]/health")]
public IActionResult HealthProbe()
{
// return 200
return Ok($"DCS Sample - HealthProbe - {_version} IP Address = {DcsNet.GetLocalIpAddress()} Environment.MachineName = {Environment.MachineName}");
}
Swagger is running at - www.somehostname.com/sample-dcs/index.html
When I click on GET and try to execute,
curl is making a call to below, and getting 404.
somehostname.westus2.cloudapp.azure.com/DCSapi/v1/DCSOrders/health
But CURL should point to this below URL, since Swagger is running at www.somehostname.com/sample-dcs
somehostname.westus2.cloudapp.azure.com/sample-dcs/DCSapi/v1/DCSOrders/health
sample-dcs might be changed in future.
Thank you in advance.
I have a controller as the following below:
using CadastroDerivativos.Domain.Interfaces.Services;
using Microsoft.AspNetCore.Mvc;
namespace CadastroDerivativos.WebApi.Controllers
{
[Route("api/equity")]
[ApiController]
public class EquityOptController : ControllerBase
{
private readonly IEquityOptService _equityOptService;
public EquityOptController(IEquityOptService equityOptService)
{
_equityOptService = equityOptService;
}
[HttpGet("{ticker}")]
public bool CheckTicker(string ticker)
{
return _equityOptService.hasTicker(ticker);
}
}
}
I can send a http request with the following url: https://localhost:44353/api/equity/ewz%20us%20-12-2021%20C41.
The problem is that I need to receive in my controller a string like the following: EWZ US 12/21/21 C41 Equity, completely as I passed it would be ideal. So, how can I pass a string like the one in the http request? I'm using the get method, is it the one I should use?
EDIT
When I try to make the request with this url: https://localhost:44353/api/equity/ewz%20us%12/21/21%20C41, I believe that the / of the date are interpreted as separating the url, causing that it is not possible to call the service on the backend.
i am developing an using Angular8 and .NET Core 3.0 in Visual Studio. I have a page with a form which is working without any issues. However when i press F5 on that page i get the following error
Failed to load resource: the server responded with a status of 405
(Method Not Allowed) [http://localhost:51871/notifications]
This is the submit function in the component class
onSubmit() {
if (this.registerForm.invalid) {
return;
}
let post: NotificationsInterface = {
email: this.registerForm.value.email,
subject: this.registerForm.value.subject,
text: this.registerForm.value.text,
};
this.http.post("Notifications", post).subscribe(result => {
console.error("ok");
}, error => console.error("error"));
}
This is the notification class in C#
public class Notifications
{
public string email { get; set; }
public string subject { get; set; }
public string text { get; set; }
}
This is the controller in C#
using Microsoft.AspNetCore.Mvc;
using HomeHelper.Models;
namespace HomeHelper.Controllers
{
[ApiController]
[Route("[controller]")]
public class NotificationsController : Controller
{
[HttpPost]
public IActionResult Post([FromBody]Notifications notification)
{
return Ok();
}
}
}
When i comment the controller part in C# the error is gone, however the data cannot be received. What is the best practice for such errors to be avoided ?
The error only occurs in the url " http://localhost:51871/notifications "
Best regards!
UPDATE: I have added the full code of the controller and the url with the specified error.
You can debug this issues by creating a get route with same end point in your controller.
when you refresh your Angular application as you have a route localhost:51871/notifications in your controller your server resolves the route and points you to the controller but as of now there is no Get method (as browser sends a get request when you refresh) so it gives you error.
I guess either to adopt to hash location strategy or try changing the angular route or you can do is all your backend api url should work if there is a api in the url path
like localhost:51871/api/notifications that will help to sort api is getting called
Try using hash location strategy.
RouterModule.forRoot(routes, {useHash: true})