Search code examples
c#asp.net-web-apiasp.net-web-api-routing

ASP.Net WebApi change this default request method mapping with action name


I am Creating a new Web API Controller named Customer. and this Controller has one Action named "Create"

I couldn't make this Action able to be requested via "GET" HTTP Request in this form

http://ip:port/api/Customer/Create?userId=x&password=y

except in this method :

public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    [ActionName("Create")]
    public MISApiResult<List<Branch>> GetCreate(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}

Is there any other solution to preserve the action name as "Create" as next.

public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    public MISApiResult<List<Branch>> Create(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}

Thanks.

Edit:

Sorry for not being clear at the first time.

According to this answer:

How does a method in MVC WebApi map to an http verb?

There is a default http method according to the action names, if it starts with Get it'll bemapped to GET HTTP Method be default otherwise it will be mapped to POST.

Is there a way to change this default mapping with a custom one so I could map an action named "Create" with "GET" Http Method for testing purpose since this way is faster for development

I tried to put HttpGet Attribute and AcceptVerbs("GET") and it still map the action with POST Http method.

I found a way like I said and it's to change the action method name into GetCreate and then put ActionName attribute with "Create" value. but is there a way to change the default mapping?

Thanks again.


Solution

  • why dont you specify route. You actual issue is using System.Web.Mvc use System.Web.Http instead

     using System.Web.Http;
     [RoutePrefix("api/Customer")]
        public class CustomerController : ApiController
        {
            [HttpGet]
            [Route("Create")]
            public MISApiResult<List<Branch>> Create(string userID, string password)
            {
                return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
            }
        }