webapi做为后端接口时在跨域调用时的注意点

来源:互联网 发布:淘宝oppo手机 编辑:程序博客网 时间:2024/05/21 03:55

比如一个典型的前端跨域调用:

$.ajax({
url: url,
data: params,
dataType: ‘jsonp’,
jsonpCallback:’jsonpcall’,
contentType: “application/json; charset=utf-8”,
type: ‘get’,
success: function (msg) {
mask.remove();
showMsg(msg + ‘success’);
if (typeof callback_s === ‘function’) {
callback_s(msg);
}
},
error: function (xhr, status, error)
{ console.log(xhr); }
});

其中jsonpCallback要求接口在返回数据时调用jsonpcall 函数,所以后台接口在返回数据时使用:

public HttpResponseMessage getFuwuShanagAll()
{
var newdata= new
{

data = fuwu.SelectFuwuShanagAll()
};
string output = JsonConvert.SerializeObject(newdata);
output = “jsonpcall(” + output + “)”;
return new HttpResponseMessage { Content = new StringContent(output, System.Text.Encoding.UTF8, “application/json”) };
}

其中对要返回的数据使用了jsonpcall()函数包裹。

要返回的数据使用了

Anonymous and Weakly-Typed Objects

的序列化。

原创粉丝点击