0
votes

This is my first question on stackoverflow and hopefully it's not because of my poor searching skill.

I am recently trying to create a log server with .net core. I started a web api project and created something like this:

    [HttpPost("/log")]
    public IActionResult Post([FromQuery] string msg, [FromQuery] string stackTrace)
    {
       ...
    }

I stored each log as an object and I can use console.log to display its value. Then I am trying to use websocket to push the log into a web client.

I am hoping to modify this tutorial https://radu-matei.github.io/blog/aspnet-core-websockets-middleware/ to suit what I need.

The tutorial project works fine. Messages are sending and receiving between web clients.

However, I couldn't integrate the tutorial web app project with my web api controllers. The "/log" api gives a 404 respond.

So I decided to start a web app template and add a default web api values controller to it (which has the attribute [Route("api/[controller]")]).

The default web pages loaded fine but api/values gives a 404 respond.

What is the correct way to add a controller with route attributes to a web app?

Thanks a lot!

2

2 Answers

0
votes

Assuming you have the following controller:

[Route("api/[controller]")]
public class MyLogController : Controller
{
    [HttpPost("log")]
    public string Post()
    {
        // your code here...
    }
}

Then you should post to URL /api/mylog/log. Default structure for the URL in WebApi is /api/<<Your Controller Name without Controller at the end>>. Custom routes defined above the methods will appended to default url. Also your route definition doesn't need to start with /.

For more details please look at: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing

Hope this helps.

0
votes

Since the both of the parameters are full sentence strings it would be better to put them in the POST body.

I, especially, recommend that you don't send the Stack trace through the query string. The query string has a maximum length (depending on the browser and possibly the web server) and the stack trace can have a lot of text.

Discussion with the details: What is the maximum possible length of a query string?

Do something like this:

    [HttpPost("log")]
    public IActionResult Post([FromBody] Log data)
    {
       ...
    }

With a Log class

public class Log
{
    public string StackTrace {get;set;}
    public string Message {get;set;}
}