MVC HttpGet属性

时间:2015-11-18 15:08:26

标签: asp.net-mvc asp.net-mvc-4

这里的MVC noob并没有从中找到一个简单的解释。

我刚刚开始研究使用MVC构建的相当大的应用程序。

在我使用的控制器中,大多数ActionResults都附加了[HttpGet]属性。所以我建立了这些代码,我自己构建了两个ActionResults,但是关闭了[HttpGet]属性。

这些调用将调用数据库层,然后将结果返回给视图。他们工作正常。当我注意到他们没有[HttpGet]时,我添加了它们,然后呼叫停止工作。我无法弄清楚为什么,或者他们必须在那里的押韵和原因。

以下是我从视图中发出的电话:

function getExcelExport() {
var activePane = $('div.tab-pane.active');

var agencyCompany = $(activePane).find('#Agency_AgencyId').val();
if (!$(activePane).find('#form0').valid()) { return false; }
var month = $(activePane).find('#CommissionMonth').val();
var year = $(activePane).find('#CommissionYear').val();

window.location = 'AgencyManagement/GetCommissionsExcel?agencyID=' + agencyCompany + '&month=' + month + '&year=' + year;
};

以及控制器中的操作:

        public ActionResult GetCommissionsExcel(string agencyid, string month, string year)
    {
        try
        {
            var as400rep = new iSeriesRepository(new iSeriesContext());
            var results = as400rep.GetCommissionExcel(agencyid, month, year);

            string xml = String.Empty;
            XmlDocument xmlDoc = new XmlDocument();

            XmlSerializer xmlSerializer = new XmlSerializer(results.GetType());

            using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, results);
                xmlStream.Position = 0;
                xmlDoc.Load(xmlStream);
                xml = xmlDoc.InnerXml;
            }

            var fName = string.Format("CommissionsExcelExport-{0}", DateTime.Now.ToString("s"));
            fName = fName + ".xls";

            byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(xml);

            return File(fileContents, "application/vnd.ms-excel", fName);
            }
        catch (Exception ex)
        {
            Log.Error(ex.Message, ex.InnerException);
            throw;
        }
    }

对此有一个简单的解释吗?

2 个答案:

答案 0 :(得分:3)

当您添加[HttpGet]并且来电已停止'工作是因为你将使用不同的HTTP动词调用该方法,例如POST

在方法上应用Http动词属性意味着to restrict an action method so that the method handles only HTTP GET requests.

当你没有使用http动词属性时它全部工作的原因是因为该动作方法可以通过所有Http动词获得。

将行动方法标记为[HttpPost],它将起作用。

[HttpPost]
public ActionResult Action(int id)
{
}

您可以为GETPOST使用相同的方法名称,但该方法需要不同的签名(重载)。

[HttpGet]
public ActionResult Action() { }

[HttpPost]
public ActionResult Action(int id) { }

这通常用于PRG模式(POST,Redirect,GET)。您可以进一步了解此here

答案 1 :(得分:2)

[HttpGet]将Action标记为仅用于GET请求的应用程序 -

请考虑以下事项:

public ActionResult DoSomething() { }

如果你要去/ DoSomething或POST / DoSomething - 将会调用该动作。

指定:

[HttpGet]
public ActionResult DoSomething() { }

确保只有在请求是GET

时才会调用此方法