get/post数据.Net后台

日期:2015-6-30 14:38 | 标签: get&post AngularJS | 阅读:601

本次探讨,使用.net一般处理程序(ashx)做实验。

GET

GET比较好说,直接使用Request对象即可以拿到数据

public void ProcessRequest(HttpContext context)
{
            string name = context.Request["name"];
            context.Response.Write("Hello " + name);
}

POST

POST则流行有两种方法,一种是直接在Request.Form中获取,二种是通过Request.InputStream获取。 第一种

public void ProcessRequest(HttpContext context)
{
         string name = context.Request.Form["name"];
         context.Response.Write("Hello " + name);
}

第二种

public void ProcessRequest(HttpContext context)
{
            System.IO.Stream stream= context.Request.InputStream;
            int length = (int)stream.Length;
            byte[] bytes= new byte[length ];
            stream.Read(bytes, 0, length );
            stream.Close();

            //转字符串并输出
            string data = Encoding.GetEncoding("utf-8").GetString(bytes);
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello " + name);
}

以上是.Net服务端的处理方式,本次请求发起方式是采用angularJs的$http域

$http({
       url:'http://localhost:8080/Service.ashx?name=pengyi',
       method:"POST",//"GET"
       headers: {
            'Content-Type': 'multipart/form-data'
       },
       data: {
              name: 'pengyi'
       }
}).success(function(data, status, headers, config){
        alert(data);
});

ps:若是要支持跨域,还得在服务端返回头添加:

 context.Response.AddHeader("Access-Control-Allow-Origin","*");//*号代表所有,请妥善使用

本次试验POST只在通过Request.InputStream获取时成功,在Request.Form中的值为null 产生的主要原因是jquery中的ajax请求和angularJS中对数据的请求包装方式不同,jquery对数据的处理使用

Content-Type: x-www-form-urlencoded

序列化的结果类似为

foo=bar&baz=moe

而angularJS对数据的处理使用

Content-Type: application/json

序列化的结果类似为

{ "foo": "bar", "baz": "moe" }

这使得有些后端不能解析POST和GET数据,.NET就中招了,所以才出现了使用Request.InputStream进行解析的情况。当然,前端也有相应的处理方式,具体参考: victorblog.com 也可以直接使用我从上述网址里面copy过来的代码,只需对主模块稍许修改则可以了:

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
 // Use x-www-form-urlencoded Content-Type
 $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

 /**
 * The workhorse; converts an object to x-www-form-urlencoded serialization.
 * @param {Object} obj
 * @return {String}
 */
 var param = function(obj) {
     var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

     for(name in obj) {
         value = obj[name];

         if(value instanceof Array) {
             for(i=0; i<value.length; ++i) {
                 subValue = value[i];
                 fullSubName = name + '[' + i + ']';
                 innerObj = {};
                 innerObj[fullSubName] = subValue;
                 query += param(innerObj) + '&';
             }
         }    
         else if(value instanceof Object) {
             for(subName in value) {
                 subValue = value[subName];
                 fullSubName = name + '[' + subName + ']';
                 innerObj = {};
                 innerObj[fullSubName] = subValue;
                 query += param(innerObj) + '&';
             }
         }
         else if(value !== undefined && value !== null)
             query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
         }

         return query.length ? query.substr(0, query.length - 1) : query;
 };

 // Override $http service's default transformRequest
 $httpProvider.defaults.transformRequest = [function(data) {
     return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
 }];
});

报错

Request header field xxx is not allowed by Access-Control-Allow-Headers in preflight response.

解决方案:

#a1
The server (that the POST request is sent to) needs to include the Access-Control-Allow-Headers
 header (etc) in its response. Putting them in your request from the client has no effect.
This is because it is up to the server to specify that it accepts cross-origin requests (and that it
 permits the Content-Type request header, and so on) – the client cannot decide for itself that a
 given server should allow CORS.

#a2
I was in the problem. by deep search i get .. For cross-domain requests, setting the content type to
 anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will
 trigger the browser to send a preflight OPTIONS request to the server. so if server does not allow it
 will throw errors. by default angular content type is application/json which is trying to send a
 OPTION request. try to overwrite angular default header . or allow it in server end. here is angular
 sample:

跨域提交全局参数

  1. 自动附加在url中,采用querystring形式
  2. 添加自定义请求头
  3. 作为form表单默认参数提交

版权声明: 署名-非商业性使用-禁止演绎 4.0 国际(CC BY-NC-ND 4.0
Copyright ©2013-2017 | 粤ICP备14081691号 | yipeng手工打造 | 联系方式