Angular POST to Web API doesn't pass data

后端 未结 3 1470
一个人的身影
一个人的身影 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:12

    Check if you have included the JSON Formatter in your configuration. It should be something like :

        System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
        config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
    

    The Content-Type=application/json only will work if you set the proper formatter.

    You can also try using [FromBody] next to your parameter type.

    0 讨论(0)
  • 2021-01-18 16:15

    Solved! Discovered this question:

    AngularJs $http.post() does not send data

    Pointing to this lovely article:

    http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

    Turns out Angular doesn't post data the same way jQuery does but you can override it with some tweaking.

    0 讨论(0)
  • 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<AgentRequest>(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);
            }
        }
    
    0 讨论(0)
提交回复
热议问题