Ajax跨域Post方法调用Web Api(NuGet配置的环境)

没安装的去NuGet安装,

然后安装,

建立Web Api项目.需要在里的WebApiConfig.cs里配置 

 config.EnableSystemDiagnosticsTracing(); //感觉这句像是跨域的开关,

            //配置返回的时间类型数据格式  ,返回Json格式的数据,并且加入时间类型的格式
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
                new Newtonsoft.Json.Converters.IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy-MM-dd hh:mm:ss"
                }
            );

 并且在Web.Config里加入

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true" />

位置

 

 

 总体来说就可以跨域了.

实验下写个小Demo

自己新建个控制器,

自己弄点儿东西,

 public class TryApiController : ApiController
    {
        [HttpPost]
        public ResponseData MethodMapping([FromBody] RequestData requestData)
        {
            if (requestData.ActionCode != null && requestData.ActionCode != "")
            {
                string command = requestData.ActionCode;
                System.Reflection.MethodInfo method = this.GetType().GetMethod(command);
                if (method != null)
                {
                    return (ResponseData)method.Invoke(this, new object[] { requestData.RequertParams });
                }
                else
                    return new ResponseData() { ErrorMsg = "请求函数名<ActionCode>不能为空", RequestStatus = "FAIL", ResponseEntity = null };
            }
            else
            {
                return new ResponseData() { ErrorMsg = "请求函数名<ActionCode>不能为空", RequestStatus = "FAIL", ResponseEntity = null };
            }
        }

        public ResponseData TheApi(string str)
        {
            ResponseData rd = new ResponseData();
            rd.ResponseEntity = str;
            return rd;
        }
    }
}
public class ResponseData
{
    public string RequestStatus { get; set; }
    public string ErrorMsg { get; set; }
    public string ResponseEntity { get; set; }
}
public class RequestData
{
    public string ActionCode { get; set; }
    public string RequertParams { get; set; }
}

这是传入一个类,第一个参数是要求调用TheApi函数, 第二个参数是给被调用的函数传入的参数,

然后写个Ajax调用,

 Ajax: function (url, data, success, error) {
        if (error) {
            $.ajax({
                type: "Post",
                url: url,
                dataType: "json",
                data: data,
                success: success,
                //error: error
            });
        } else {
            $.ajax({
                type: "Post",
                url: url,
                dataType: "json",
                data: data,
                success: success,
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    // alert(XmlHttpRequest.responseText);
                }
            });
        }
    },

Cmd.Ajax("http://localhost:8088/api/TryApi/MethodMapping", { ActionCode: "TheApi", RequertParams: "haha" }, function (result) {
                alert(result.ResponseEntity)
            })

 

那个haha就会被弹出来...写的很草,主要是备忘,

当然也可以用Cors.


 

posted @ 2016-10-12 14:37  SaYes  阅读(552)  评论(0编辑  收藏  举报