Http 405 MethodNotAllowed on ASP.NET Core endpoint - c#

Vs.js code - here are axios.delete and mounted sections:
mounted() {
this.getCreated();
},
deleteRequest(id) {
axios.delete("http://localhost:32961/api/request/delete"+id)
.then(() => {
this.getCreated()
})
.catch((err) => console.error(err));
},
C# code - this is the backend part (controller):
[Route("delete/{id}")]
[HttpDelete]
public IActionResult Delete([FromBody] Request request)
{
_db_Context.Requests
.FirstOrDefault(a => a.RequestId == request.RequestId);
_db_Context.Requests.Remove(request);
_db_Context.SaveChanges();
return Ok(request);
}
I think I'm making a mistake in the vue.js axios.delete part. I am getting error code 405. How can I fix it?

You should change
axios.delete("http://localhost:32961/api/request/delete"+id)
to
axios.delete("http://localhost:32961/api/request/delete/"+id)
And do this in the C# API code:
[Route("delete/{id}")]
[HttpDelete]
public IActionResult Delete(int id)
{
_db_Context.Requests
.FirstOrDefault(a => a.RequestId == request.RequestId);
_db_Context.Requests.Remove(request);
_db_Context.SaveChanges();
return Ok(request);
}
Or if you call Delete API with query string of id you should set FromUri in api.
See this link

Abbas Aryanpour is right in pointing out the missing / in your code. But I think the error message should be 404, not 405.
I think this should be related to your asp.net core back-end code not setting cross-domain, or you have set cross-domain, but did not notice the execution order of middleware, so it may cause cross-domain not to take effect.
Official doc:
1.Troubleshoot connection errors
2. Cross-origin resource sharing

Related

How to add custom 401 error message in ASP .NET core 6

Here is my controller code.
my controller return 401 status code successfully.
How to return a 401 error message with my custom message
[HttpGet]
[Authorize(Roles = "reader")]
public async Task<IActionResult> GetAllBlogsAsync()
{
// get data from repository
var blogs = await blogRepository.GetAllAsync();
// mapping Domain to DTO
var blogsDTO = mapper.Map<List<Models.DTO.Blog>>(blogs);
// return results
return Ok(blogsDTO);
}
My expected Output is "401 UnAuthorized"
Advance Thanks.
you can use the Unauthorized method like below to return.
return Unauthorized("401 UnAuthorized");
I think what you need is a custom implementation of the attribute as explained in this post:
How to return custom message if Authorize fails in WebAPI

ASP.NET Core Invoke API via Postman

So i have this ASP.NET Core on my local machine, i have installed the prerequisites and after running the application locally, the response was correct from the web browset that it was not found.
Okay, i am trying to invoked this API via Postman and i couldnt determine why i cant access it though i already checked the routings.
Below is the sample template
[HttpGet]
[Route("Details")]
public async Task<IActionResult> GetDetails(string value = null)
{
var response = new ListModelResponse<SomeModel>() as IListModelResponse<SomeModel>;
try
{
response.Model = await GetDetailsRepository
.GetDetailsSS(value)
.Select(item => item.ToViewModel())
.OrderBy(item => item.Name)
.ToListAsync();
}
catch (Exception ex)
{
response.DidError = true;
response.ErrorMessage = ex.Message;
}
return response.ToHttpResponse();
}
And in application insights of visual studio, i can see that it is invoking the API but it seems it can't get through.
Check this insights snippet
Other API's are working fine, it seems that i am missed something that i can't figure out right now.
For the routing i have this.
[Route("api/[controller]")]
I have also checked the Token and as i parsed it, i am getting the required info to access this API.
Thanks Lads!
It doesn't seem that you have the name of the controller in the request url.
api/[controller]/Details?value=CAT...
This error is due to the incorrect url present in the request. The correct URL has to be https://localhost:44309/api/your-controller-name/Details?value=CAT
ie. If the Controller name is ProductsController, then the URL has to be https://localhost:44309/api/Products/Details?value=CAT.
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpPost("Details")]
public async Task<IActionResult> GetDetails(string value = null)
{
...
}
}

Not able to fetch response from HttpClient POST method using Angular 7, .net core 2.2

I am creating quite basic implementation of CRUD methods using Angular and ASP.NET Core in the back end.
The back-end work perfectly, but cannot get the response after redirect action.
Let me bring the code:
the C# Controller bit:
[HttpPost]
[ProducesResponseType(200, Type = typeof(IActionResult))]
public async Task<ActionResult<CapCustomerResponseDto>> CreateCustomer([FromBody] CreateCustomerRequestDto request)
{
try
{
///. .. *creating command*
await _createCustomercommandHandler.Execute(command);
return CreatedAtRoute("GetCapCustomer", new { id = command.Id.ToString() }, command);
}
catch (Exception e)
{
// Some custom handling
}
}
So at the end we have the magical CreatedAtRoute() method, which redirects to the get controller
the Angular 7 httpClient implementation
addCustomer(customer): Observable<Customer> {
return this.http.post<Customer>(apiUrl, customer, httpOptions).pipe(
tap((customer: Customer) =>
console.log(`added customer w/ id=${customer.customerId}`)
),
catchError(this.handleError<Customer>("addCustomer"))
);
}
which actually returns nothing.
My customer is added properly, I can see it in the database. When using swagger, I can see the controllers working. Even in Network monitor.
but I have no clue how to retrieve the newly created customer response into my TS classes
Instead I get this:
Error: The requested path contains undefined segment at index 1
from Console
Question.
How can I make this work?

Cant get ASP.NET MVC 6 Controller to return JSON

I have an MVC 6 project in which i am using Fiddler to test out Web API. If i take the following controller action which uses EntityFramework 7 to return a List. Then the html will render fine.
[HttpGet("/")]
public IActionResult Index()
{
var model = orderRepository.GetAll();
return View(model);
}
But when i try to return a Json response instead i get a 502 error.
[HttpGet("/")]
public JsonResult Index()
{
var model = orderRepository.GetAll();
return Json(model);
}
Any Idea on why the object isnt serialized into json correctly?
First of all you can use IEnumerable<Order> or IEnumerable<object> as return type instead of JsonResult and return just orderRepository.GetAll(). I recommend you to read the article fr additional information.
About another error with Bad Gateway. Try to add Newtonsoft.Json in the latest version 8.0.2 to dependencies in package.json and to use use
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
By the way one can reproduce the error "HTTP Error 502.3 - Bad Gateway", which you describes if I just set breakpoint on the return statement of working code and wait long enough. Thus you will see the error "HTTP Error 502.3 - Bad Gateway" very soon on many common errors.
You can consider to us more helpful serialization options. For example
services.AddMvc()
.AddJsonOptions(options => {
// handle loops correctly
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// use standard name conversion of properties
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
// include $id property in the output
options.SerializerSettings.PreserveReferencesHandling =
PreserveReferencesHandling.Objects;
});

MVC5 app doesn't hit my WebAPI2 POST method for creating new records

I have an MVC5 application, ASP.NET, that, when creating a new record and clicking submit, it calls my WebAPI (version 2 - the new one) to insert the record into the database. Problem is, it's not hitting the POST method in my WebAPI. Anyways, here's my MVC5, front end application code for "Create":
[HttpPost]
public ActionResult Create(BulletinBoard bulletinBoard)
{
bulletinBoard.CreatedDate = DateTime.Now;
bulletinBoard.CreatedBy = HttpContext.User.Identity.Name;
response = client.PostAsJsonAsync("api/bulletinboard", bulletinBoard).Result;
if (response.IsSuccessStatusCode)
{
return View("Index");
}
else
{
LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
"Cannot create a new feedback record due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
return View("Problem");
}
}
I already defined "client" in my constructor and gave it the base URL for my WebAPI - keep in mind that GET works - so it's not a problem with my URL. I can also manually go to my WebAPI URL and get data back in my browser.
Here's my WebAPI code:
// POST api/bulletinboard
public HttpResponseMessage PostBulletinBoard(BulletinBoard bulletinBoard)
{
if (ModelState.IsValid)
{
db.BulletinBoards.Add(bulletinBoard);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, bulletinBoard);
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
This worked when I was using WebAPI version 1 which had a different naming convention for the GET and POST and PUT methods.
So, when the URL for the POST request is called (the line that's response = client.PostAsJsonAsync...), the request never hits my POST method in my WebAPI and consequently, no records are inserted into my database. What am I doing wrong?
According to the comments it appears that you have POSTed invalid data (according to the validation rules you defined in your BulletinBoard model) and this validation simply fails. So to fix the issue make sure you are sending valid data.
I think there might be a few reasons why it doesn't hit your post method. Here is my example of Post method. The things you should note is method name and FromBody attribute
public async Task<HttpResponseMessage> Post([FromBody]FoodProduct foodProduct)
{
UnitOfWork.FoodRepository.Edit(foodProduct);
await UnitOfWork.SaveAsync();
return Request.CreateResponse(HttpStatusCode.OK);
}
I also like to use this new RoutePrefix Attribute on my controller, it works perfectly and looks good.
[RoutePrefix("api/Food")]
public class FoodController : BaseApiController
{
///some code here
}

Categories

Resources