JsonRequestBehavior.AllowGet不适用于HttpGet

时间:2017-03-25 04:32:13

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

我已经阅读了JSONRequestBehavior.AllowGet的MSDN文档以及SO的许多答案。我试验过,我仍然感到困惑。

我有以下行动方法。如果我在我的ajax调用中使用POST方法,它工作正常。如果我在我的ajax调用中使用GET方法,它将失败,状态为404(资源未找到)。那么,问题是JsonRequestBehavior.AllowGet枚举在这个Json方法中究竟做了什么? MSDN文档说:允许来自客户端的AllowGet HTTP GET请求。 (https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior(v=vs.118).aspx),但是为什么在我的ajax调用中使用GET方法时它会失败?将属性从HttpPost更改为HttpGet没有帮助,它使用POST或GET方法失败。

 [HttpPost]
    public JsonResult Create(Model m)
    {
        m.Ssn = "123-45-8999";
        m.FirstName = "Aron";
        m.LastName = "Henderson";
        m.Id = 1000;
        return Json(m, JsonRequestBehavior.AllowGet);
    }

    public class Model
    {
       public int Id { get; set; }
       public string Ssn { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
    }

这是我的jQuery ajax调用:

    $(function () {
        console.log("hola");

        $("button").on("click", function () {
            $.ajax({
                method: "POST", //Try changing this to GET and see.
                url: "Home/Create",
                data: { Id: 123, Ssn: "585-78-9981", FirstName: "John", LastName: "Smith" }
            })
    .done(function (msg) {
        alert("Data Saved: " + msg);

        });

  });

    })

2 个答案:

答案 0 :(得分:2)

404 (Resource not found)表示找不到该方法(与JsonRequestBehavior无关)。

更改您的ajax以使用

$.ajax({
    url: "/Home/Create", // note leading forward slash
    ....

或更好,使用url: '@Url.Action("Create", "Home")',正确生成您的网址。

答案 1 :(得分:1)

404是由于属性,与JSON上的“AllowGet”无关。

您需要一个或另一个[HttpVERB]属性......不是两个属性。

如果是您的情况,这将有效。

   [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]

您应该查看此well documented post

AllowGet将简单地允许JSON响应在GET场景中无异常地工作。如果不这样做,您会看到message

  

此请求已被阻止,因为敏感信息可能是   当在GET请求中使用它时向第三方网站公开。   要允许GET请求,请将JsonRequestBehavior设置为AllowGet。

相关问题