【问题标题】:How to pass data to Asp.net Web API through Windows Phone 7如何通过 Windows Phone 7 将数据传递给 Asp.net Web API
【发布时间】:2013-01-26 16:45:03
【问题描述】:

我想知道在使用 Windows Phone 7 和 asp.net web api 时如何来回发送数据?

我的 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; }
}

我的 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);
}

得到的网址是这样的:http://localhost:50570/api/user/get?email=c

但 Vm 始终为空。

【问题讨论】:

  • 你的VerifyUserVm怎么样?

标签: c# windows-phone-7 asp.net-web-api webclient query-parameters


【解决方案1】:

Web.Api 以会话方式绑定来自 URL 的简单参数(int、string 等)和来自请求正文的复杂类型(任何其他自定义类型)。

如果你想从url绑定一个复杂类型VerifyUserVm(例如:查询字符串)你需要用FromUriAttribute注释参数:

public HttpResponseMessage Get([FromUri]VerifyUserVm vm)
{
     //..
}

还有一点:属性的大小写应该匹配:

在您的 VM 中,Email 带有大写的 E,但您发送的 email 带有小写的 e。

所以你需要像这样构建你的参数:

uri.Query = "Email=" + txtEmail.Text;

进一步阅读:How WebAPI does Parameter Binding

【讨论】:

  • 我一直在研究 RestSharp 这会自动为我完成还是会遇到同样的问题?
  • 我没有使用 RestSharp 的经验,所以我不知道。但据我所知,RestSharp 是一个客户端库,所以如果您仍然在服务器端使用 web.api,我不知道它对您的情况有何帮助。
  • 好的。我试过了,现在我得到了一个 Vm 对象,但没有填充电子邮件。
  • 属性的大小写应该匹配。在您的 VM 中,Email 带有大写字母 E,但您发送的 email 小写字母 e。将其更改为:uri.Query = "Email=" + txtEmail.Text;
猜你喜欢
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2013-01-15
  • 1970-01-01
相关资源
最近更新 更多