Angular POST to Web API doesn't pass data

后端 未结 3 1463
一个人的身影
一个人的身影 2021-01-18 15:44

I\'ve been writing code against ASP.NET Web API for a while now with jQuery and I\'m starting something new in Angular (writing against the same Web API backend.)

I\

3条回答
  •  醉梦人生
    2021-01-18 16:24

    I solved this by below codes:

    Client Side:

         $http({
                    url: me.serverPath,
                    method: 'POST',
                    data: data,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                }).
                    success(function (serverData) {
                        console.log("ServerData:", serverData);
        ......
    

    Notice that data is an object.

    On the server (ASP.NET MVC):

    [AllowCrossSiteJson]
            public string Api()
            {
                var data = JsonConvert.DeserializeObject(Request.Form[0]);
                if (data == null) return "Null Request";
                var bl = Page.Bl = new Core(this);
    
                return data.methodName;
            }
    

    and 'AllowCrossSiteJsonAttribute' is needed for cross domain requests:

    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
                base.OnActionExecuting(filterContext);
            }
        }
    

提交回复
热议问题