[英]How to pass data to Asp.net Web API through Windows Phone 7
I am wondering how do you send data back and forth when using Windows Phone 7 and asp.net web api? 我想知道在使用Windows Phone 7和asp.net web api时如何来回发送数据?
I have this method in my webapi 我的webapi中有这种方法
public HttpResponseMessage Get(VerifyUserVm vm)
{
if (ModelState.IsValid)
{
userService.ValidateUser(vm.Email);
if (userService.ValidationDictionary.IsValid)
{
HttpResponseMessage reponse = Request.CreateResponse(HttpStatusCode.OK, userService.ValidationDictionary.ModelState["Success"]);
return reponse;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, userService.ValidationDictionary.ModelState);
}
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
public class VerifyUserVm
{
[Required]
public string Email { get; set; }
}
and this code in my WP7 这个代码在我的WP7中
private void btnSignIn_Click(object sender, RoutedEventArgs e)
{
string urlPath = String.Format(WebApiHelp.ApiUrl,"user","get");
UriBuilder uri = new UriBuilder(urlPath);
uri.Query = "email=" + txtEmail.Text;
webclient.OpenReadAsync(uri.Uri);
}
the url that gets made is this: http://localhost:50570/api/user/get?email=c
得到的网址是:
http://localhost:50570/api/user/get?email=c
but the Vm is always null. 但是Vm总是为空。
Web.Api conversationally binds simple parameters (int, string, etc.) form the URL and complex types (any other custom type) from the request body. Web.Api以对话方式将简单参数(int,string等)从请求正文中绑定到URL和复杂类型(任何其他自定义类型)。
If you want to bind a complex type VerifyUserVm
from the url (eg: query string) you need to annotate the parameter with the FromUriAttribute
: 如果要从url绑定复杂类型
VerifyUserVm
(例如:query string),则需要使用FromUriAttribute
注释参数:
public HttpResponseMessage Get([FromUri]VerifyUserVm vm)
{
//..
}
One more thing: the casing of the properties should match: 还有一件事:属性的外壳应该匹配:
In your VM you have Email
with a uppercase E
but you send email
with a lower case e
. 在您的虚拟机中,您使用大写字母
E
Email
,但是您发送的email
包含小写字母e
。
So you need to build your parameter like this: 所以你需要像这样建立你的参数:
uri.Query = "Email=" + txtEmail.Text;
For further reading: How WebAPI does Parameter Binding 进一步阅读: WebAPI如何进行参数绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.