我一直用成功与阿贾克斯果园模块一会儿防伪选项。最近,我一直想从使用默认的ContentType =应用/的X WWW的形式urlen codeD变化;字符集= UTF-8到一个JSON有效载荷(的ContentType =应用/ JSON')
I have been successfully using the AntiForgery option with Ajax in Orchard Modules for a while. Recently, I have been wanting to change from using the default ContentType = 'application/x-www-form-urlencoded; charset=UTF-8' to a JSON payload (ContentType='application/JSON').
当我这样做,我得到由ASP.NET引发的异常A所需的防伪标记不提供或无效。。 OK,但我怎么去添加__RequestVerificationToken而preserving JSON有效载荷?
As soon as I do this I get an exception thrown by ASP.NET 'A required anti-forgery token was not supplied or was invalid.'. OK, but how do I go about adding the __RequestVerificationToken while preserving JSON payload?
有关参考,在这里是code我使用的是:
For reference, here is the code I'm using:
var config = { url: url, type: "POST", data: data , dataType: "json", contentType: "application/json; charset=utf-8" }; $.ajax(config);控制器(带有A所需的防伪标记不提供或无效。它得到这里之前炸毁):
Controller (blows up with 'A required anti-forgery token was not supplied or was invalid.' before it gets here):
[HttpPost] public ActionResult Update(ShoppingCartItemVM[] items) { // do stuff }这是果园防伪包装的或的MVC防伪功能的限制吗?还是我太傻了(再次)?
Is this a limitation of the Orchard AntiForgery wrapper or of the MVC AntiForgery functionality? Or am I being stupid (again)?
推荐答案吉斯卡尔是正确的。我会挖一个深一点。
Giscard is correct. I'll dig a bit deeper.
请注意:只有后结果在果园控制器需要防伪造令牌。因此,有以下的要求,记住使用JSON的请求的获取了。
Note: Only the "post" results in orchard controller require the anti forgery token. So there is less of a requirement to remember that where using a "Get" in a request for json.
通常你会希望不仅仅是请求令牌发送更多数据。在这种情况下,你与你的要求发送数据对象必须包含__RequestVerificationToken值。在这种情况下,jQuery是有用的,例如:
Often you will want to send more data than just the request token. In that case the 'data' object you send with your request must contain that __RequestVerificationToken value. In that case jQuery is useful for example:
var defaultPostValues = { __RequestVerificationToken:'@Html.AntiForgeryTokenValueOrchard()', id: 1, ..etc.. }; var myValues = { answers: [1,5,5,10] }; var data = $.extend({}, defaultPostValues, myValues); var config = { url: url, type: "POST", data: data , dataType: "json", contentType: "application/json; charset=utf-8" }; $.ajax(config);该防伪标记也可以每个模块定义被关闭(如果我没有记错?)。Module.txt
The anti-forgery token can also be turned off per module definition (if I remember correctly?). Module.txt
Name: Polls AntiForgery: false Author: Matt ... removed for brevity Features: Polls ... etc不过,我会建议使用防伪如果你的电话是果园的模块中,并且当且仅当是由外部请求其他地方需要你的数据禁用。不过,我想在乌节建议的WebAPI的这种情况下,但创建一个全新的故事,或许有可能移动远超出范围。
However I would recommend using the antiforgery if your calls are within Orchard's modules, and disabling if and only if your data is needed else where by external requests. But I would recommend WebAPI within Orchard for that case but that creates a whole new story and probably likely moves far out of scope.
更多推荐
防伪和JSON不相容?
发布评论