在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Using jQuery to POST [FromBody] parameters to Web API时间2013-04-04 00:28:17 Encosia 原文 http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/ ASP.NET Web API has been one of my favorite recent additions to ASP.NET. Whether you prefer a RESTful approach or something more RPC-oriented, Web API will do just about anything you need . Even if you’re still using ASP.NET WebForms, Web API still has you covered – a nice example of the “One ASP.NET” philosophy that’s finally beginning to come together. However, ASP.NET Web API throws an unintuitive curveball at you when you want to accept simple primitive types as parameters to POST methods. Figuring this issue out is particularly confusing because it’s one of the rare parts of Web API that violates the principle of least astonishment . Because of that, using jQuery to interact with those methods requires a slight contortion that seems strange at first, but makes sense once you understand why it’s necessary. In this post, I’ll briefly describe the underlying issue and show you how jQuery can be convinced to work around the issue. POSTing primitive parameters to Web APIThere are three things you need to know about Web API if you want to go the route of POSTing a primitive type (e.g. string, int, or bool) to a method. For example, say you’re working with this straightforward POST method in a Web API controller named // POST api/values public string Post(string value) { return value; } You might try POSTing a value into that Web API method using a standard jQuery $.post('/api/values', { value: 'Dave' }); If you inspect the server’s response to that request, you’ll be greeted with a bewildering 404 error: Confronted with that response, it’s only natural to treat the problem as an issue with your routing configuration and debug from there, but that’s not the issue. 1. Parameters must be marked as [FromBody]As it turns out, the reason for that 404 error isn’t a routing problem. ASP.NET correctly identifies our The reason for that is a twofold mismatch between the required parameter that Web API expects to accompany requests to our
// POST api/values public string Post([FromBody]string value) { return value; } I can’t say that I understand why this extra hassle is necessary, especially since it wasn’t required in WCF Web API and preliminary versions of ASP.NET Web API , but it’s easy enough as long as you’re aware that it needs to be present. Adding 2. Only one parameter per methodSpeaking of the parameters to our method, another potentially confusing thing about accepting Attempting to accept multiple parameters from the POST body will result in a (refreshingly decipherable) server-side error along these lines:
It’s possible to circumvent this limitation by using manual parsing techniques, but that seems antithetical to Web API and model binding to me. If you want Web API to automatically convert POST data to your I believe the thinking here is that, especially in a RESTful API, you’ll want to bind data to the single resource that a particular method deals with. So, pushing data into several loose parameters isn’t the sort of usage that Web API caters to. This limitation can be a bit confusing when you’re coming from WebForms or MVC though, and trying work around it feels like going against the grain of the framework. So, if I need to accept more than one POST parameter, I just define a quick view model. In other words, don’t try to do this: public string Post([FromBody]string FirstName, [FromBody]string LastName) { return FirstName + " " + LastName; } Instead, work with the framework and do something like this if you need to accept more than a single parameter: // DTO or ViewModel? Potato or potato, IMO. public class PersonDTO { public string FirstName { get; set; } public string LastName { get; set; } } public string Post(PersonDTO Person) { return Person.FirstName + " " + Person.LastName; } 3. [FromBody] parameters must be encoded as =valueThe final hurdle remaining is that Web API requires you to pass Instead of the fairly standard This part is, by far, the most confusing part of sending primitive types into a Web API POST method. Not too bad once you understand it, but terribly unintuitive and not discoverable. What not to doNow that we’ve covered what you need to know about the server-side code, let’s talk about using jQuery to POST data to // POST api/values public string Post([FromBody]string value) { return value; } You’ll have a hard time finding a jQuery // Value will be null. $.post('api/values', value); // Value will be null. $.post('api/values', { key: value }); Unfortunately, neither of those work with Web API in the case of Making it workThere are two ways to make jQuery satisfy Web API’s encoding requirement. First, you can hard code the $.post('api/values', "=" + value); Personally, I’m not a fan of that approach. Aside from just plain looking kludgy, playing fast and loose with JavaScript’s type coercsion is a good way to find yourself debugging a “wat” situation . Instead, you can take advantage of how jQuery encodes object parameters to $.post('api/values', { '': value }); If the data parameter has properties with empty string keys, jQuery serializes those properties in the form of 相关主题如果你感兴趣喜 欢 收 藏 分享该文章分享到 该来源最新文章
请 |
请发表评论