WebApi Dictionary 跨域问题

问题描述

使用WebApi编写通用服务,小程序POST调用,服务参数获取正常,页面POST调用,服务参数无法获取

代码示例

WebApi服务

        // POST: api/Test
        public string Post(Dictionary dic)
        {
            return dic.ToString();
        }

小程序调用

wx.request({
      url: "http://localhost:24739/api/Test",
      method: 'POST',
      data: {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3'
      },
      success: function (res) {
        debugger
      },
      fail: function (res) {
        debugger
      }
    })
WebApi Dictionary<string, object> 跨域问题_第1张图片
小程序调用正常

WebApi Dictionary<string, object> 跨域问题_第2张图片
小程序调用监视

页面调用

        var url = "http://localhost:24739/api/Test";
        var data = {
            'key1': 'value1',
            'key2': 'value2',
            'key3': 'value3'
        };
        $.ajax({
            url: url,
            method: 'POST',
            dataType: "json",
            //contentType: "application/x-www-form-urlencoded", //默认
            //contentType: "multipart/form-data", 
            //contentType: "application/json", 
            data: data,//JSON.stringify(data),
            success: function (res) {
                debugger
            },
            fail: function (res) {
                debugger
            }
        })
WebApi Dictionary<string, object> 跨域问题_第3张图片
页面调用无法获取

WebApi Dictionary<string, object> 跨域问题_第4张图片
页面调用监视

问题分析

对比发现主要为content-type不同,但指定页面contentType非默认后,提示跨域相关信息

WebApi Dictionary<string, object> 跨域问题_第5张图片
修改contentType

方法一,同源访问

将测试页面拷贝至服务端口下,再次调用,正常解析


同域访问

WebApi Dictionary<string, object> 跨域问题_第6张图片
正常解析

方法二,使用[FromBody]接收,再转换合适类型

WebApi服务

    public class dic {
        public string strJson { get; set; }
    }

        // POST: api/Test
        public string Post([FromBody]dic dic)
        {
            //转json
            JObject json = JObject.Parse(dic.strJson);
            //转字典
            Dictionary k = StringToDictionary(dic.strJson);
            //......
            return "";
        }

页面调用

var url = "http://localhost:24739/api/Test";
        var data = {
            "strJson": "{ 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }"
        };
        $.ajax({
            url: url,
            method: 'POST',
            dataType: "json",
            //contentType: "application/x-www-form-urlencoded", //默认
            //contentType: "multipart/form-data", 
            //contentType: "application/json", 
            data: data,
            success: function (res) {
                debugger
            },
            fail: function (res) {
                debugger
            }
        })
WebApi Dictionary<string, object> 跨域问题_第7张图片
正常解析

总结

WebApi使用特殊参数接收时,可逐步排除问题,适当转换思路常常有意外的惊喜

ajax跨域常见解决办法:
1.JSONP仅支持GET
2.CORS设置访问域总有问题,测试未成功

另:nodejs、小程序之类貌似天生就能很好支持跨域

你可能感兴趣的:(WebApi Dictionary 跨域问题)