TAGS :Viewed: 6 - Published at: a few seconds ago

[ ASP.NET 5 WebAPI ]

I am creating API post methods in ASP.NET 5 webapi. I have a requirement that I need to create overloaded post methods as follows.

[HttpPost]
public bool LogInfo([FromBody]LogEventModel value)
{
}


[HttpPost]
public bool LogInfo (String strInformation)
{
}

I tried multiple options to set the routing parameters as follows.

[HttpPost("LogInfo/{strInformation}")]

(or)

[Route("LogInfo/{strInformation}")]

But its not working. I hope I am messing up something here. Can anyone help ?

Answer 1


I don't think this is possible anymore. Because of the fact that Controllers and Web API Controllers are now the same thing, routing has been unified also. You can read more about it here.

So what I would do is, this is my controller code:

    public class HomeController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        ViewBag.Title = $@"{nameof(HomeController)}-{nameof(Index)}";
        return View();
    }

    [HttpPost]
    [Route("home/setsomething2", Name = "SetSomething2")]
    public void SetSomething([FromBody]SomeValueModel someValue)
    {
        var value = someValue;
    }


    [HttpPost]
    [Route("home/setsomething1", Name = "SetSomething1")]
    public void SetSomething(String someValue)
    {
        var value = someValue;
    }
}

public class SomeValueModel
{
    [JsonProperty("somevalue")]
    public string SomeValue { get; set; }
}

And this is how I called it from the view Index.cshtml:

    function postSomething1() {
    var url = "@Url.RouteUrl("SetSomething1", new {someValue = "someValue"})";
    $.post(url)
        .done(function () {
            alert("Succes!");
        })
        .fail(function (response) {
            console.log(response);
            alert("Fail!");
        });
}
function postSomething2() {
    var url = "@Url.RouteUrl("SetSomething2")";
    $.ajax({
        contentType: 'application/json',
        data: JSON.stringify({ "somevalue": "myvalue" }),
        dataType: 'json',
        success: function () {
            alert("Succes!");
        },
        error: function () {
            alert("Error!");
        },
        processData: false,
        type: 'POST',
        url: url
    });
}

You could however make the routing of SetSomething2 more RESTful, like:

[Route("home/setsomething/{someValue}", Name = "SetSomething2")]

Note: Notice how the path 'home/setsomething/' is cleaned from numbers, so this would be my prefered way to go.

And if you REALLY don't want to make different routes you can't use named routes. So you'll have to ditch the names like:

[Route("home/setsomething")]

And:

[Route("home/setsomething/{someValue}")]

And then call them in jQuery like for instance:

var url = "home/setsomething/somevalue";

Answer 2


Here is what I do.

I prefer specifying routes for each controller by annotating them with:

[Route("[controller]/[action]")]

Then an action may look like:

[HttpPost]
[ActionName("GetSomeDataUsingSomeParameters")]
public List<Thing> GetSomeDataUsingSomeParameters([FromBody] MyParameters parms)
{
    return Repo.GetData(parms);
}

The request may look like:

http://myhost/mycontroller/GetSomeDataUsingSomeParameters

The parameters are passed as a Json structure in the body by the POST method. For example:

{"Parameter1":1,"Parameter2":"a string"}

The request should also specify:

Content-Type: application/json

So let's say your class Thing is:

public class Thing
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Then the response could be (with two things found in the database):

[{"Id":1,"Name":"First thing"},{"Id":2,"Name":"Another thing"}]