jQuery POST. Can't get Request parameters using custom httphandler

天涯浪子 提交于 2020-01-03 18:59:22

问题


I have a jQuery post method with JSON data included.

In my httphandler, in the processRequest method, Request["Operation"] is null and none of my data is posted. I am in a SharePoint 2010 environment.

 public void ProcessRequest(HttpContext context)
    {
        try
        {
            string operation = context.Request["Operation"]; // Returns null

My JavaScript is as follows:

function CallService(serviceData, callBack) {

$.ajax({
    type: "POST",
    url: ServiceUrl,
    data: { Operation : "activate"},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        callBack(result);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(XMLHttpRequest.responseText);
    }
});

In the debugger in VS I can't find the posted values when I evaluate the HttpContext. In Firebug, the value is posted as valid JSON data. Any reason why I cant get the parameters?

Any help appreciated.


回答1:


Thanks for all your input guys. I have decided to read the input stream of the request instead and get a key value pair from that. I can access all my params that way.

I am also using the $.toJSON() function to pass my parameters to the Ajax call. The JsonConvert class is from JSON.Net assembly from Newtonsoft. I use it a lot and would highly recommend using it if you use any json serialisation stuff.

By the way, changing the quotes around the input params did work. I want to keep using one generic ajax function and use $.toJSON function and generally pass an object with all my parameters as the post data.

TextReader reader = new StreamReader(context.Request.InputStream);
        Dictionary<string, string> requestParams = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());      
        try
        {

            switch (requestParams["operation"])



回答2:


I changed contentType to application/x-www-form-urlencoded and it did a trick




回答3:


Maybe you're being restricted by the Same Origin Policy. Is ServiceUrl at the same hostname and domain as the calling page?




回答4:


Why are you overriding the contentType option in your $.ajax() call? If you omit that, do you still see null being sent in for the Operation value?

Also, I think the proper formatting for JSON data would be:

{"Operation": "activate"}

I think the JSON spec is specific about that, but most frameworks aren't as strict.



来源:https://stackoverflow.com/questions/3248526/jquery-post-cant-get-request-parameters-using-custom-httphandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!