Purpose of ActionName

What's the benefit of setting an alias for an action method using the "ActionName" attribute? I really don't see much benefit of it, in providing the user the option to call an action method with some other name. After specifying the alias, the user is able to call the action method only using the alias. But if that is required then why doesn't the user change the name of the action method rather then specifying an alias for it?

I would really appreciate if anyone can provide me an example of the use of "ActionName" in a scenario where it can provide great benefit or it is best to use.


It allows you to start your action with a number or include any character that .net does not allow in an identifier. - The most common reason is it allows you have two Actions with the same signature (see the GET/POST Delete actions of any scaffolded controller)

For example: you could allow dashes within your url action name http://example.com/products/create-product vs http://example.com/products/createproduct or http://example.com/products/create_product .

public class ProductsController {

    [ActionName("create-product")]
    public ActionResult CreateProduct() {
        return View();
    }

}

It is also useful if you have two Actions with the same signature that should have the same url.

A simple example:

public ActionResult SomeAction()
{
    ...
}

[ActionName("SomeAction")]
[HttpPost]
public ActionResult SomeActionPost()
{
    ...
}

我在用户下载报告时使用它,以便他们可以轻松地将他们的csv文件直接打开到Excel中。

[ActionName("GetCSV.csv")]
public ActionResult GetCSV(){
    string csv = CreateCSV();
    return new ContentResult() { Content = csv, ContentEncoding = System.Text.Encoding.UTF8, ContentType = "text/csv" };
}
链接地址: http://www.djcxy.com/p/23362.html

上一篇: 如果使用ActionName MVC属性装饰,请获取Action Method原始名称

下一篇: ActionName的用途