当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc 4 - Web API action names

问题描述:

I'm playing with ASP.NET Web API and I have the following:

public Guid GetLogon(string username, string password)

{

return new X.Authentication().Logon(username, password);

}

public void PostLogoff(Guid sessionId)

{

new X.Authentication().Logoff(sessionId);

}

This is being called from the client side as follows:

$(document).ready(function () {

logon("MyUsername", "MyPassword", function (guid) {

$("#sessionId").html(guid);

logoff($("#sessionId").html(), function () {

//Logged out action here

});

});

});

This all works, but I don't like to have to prefix the Action names with the http verb, like GetLogon or PostLogoff. Is there a way to make them just Logon and Logoff?

I tried the following, which didn't work:

[System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)]

public Guid Logon(string username, string password)

{

return new X.Authentication().Logon(username, password);

}

[System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)]

public void Logoff(Guid sessionId)

{

new X.Authentication().Logoff(sessionId);

}

Thank you in advance

网友答案:

Not sure if this is the cause, but in my APIController the AcceptVerbs attribute is in a different namespace:

System.Web.Http.AcceptVerbs

The [HttpGet] and [HttpPost] attribute are in the same namespace

I have a number of regular MVC controllers in the same project; they use the namespace you have described above, but not the API Controllers

Try this:

[System.Web.Http.AcceptVerbs("GET")]
public Guid Logon(string username, string password)
{
    return new X.Authentication().Logon(username, password);
}

[System.Web.Http.AcceptVerbs("POST")]
public void Logoff(Guid sessionId)
{
    new X.Authentication().Logoff(sessionId);
}
网友答案:

ASP.NET Web API will try to guess the method if you start the action name with Get, Post, Put or Delete. For example:

public void DeleteItem(int id)
{
    ...
}

Will work and system will find out that it will be triggered by DELETE.

As a backward compatibility, [HttpGet] etc attributes are supported.

分享给朋友:
您可能感兴趣的文章:
随机阅读: