我有一个称为PostUserAccount的模型,并且我尝试使用Entity Framework在ApiController中将其作为参数使用生成具有读/写操作的控制器时的正常方式使用
由控制器生成器生成的示例:
// POST api/Profile
public HttpResponseMessage PostUserProfile(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
...etc
我正在使用的代码:
// POST gamer/User?email&password&role
public HttpResponseMessage PostUserAccount(PostAccountModel postaccountmodel)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
}
if (postaccountmodel == null) return Request.CreateResponse(HttpStatusCode.BadRequest, "model is null");
...etc
无论出于何种原因,在这种情况下,postaccountmodel为null,运行此api命令将返回“ model is null”。有任何想法吗?
这是有问题的模型
public class PostAccountModel
{
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public string Role { get; set; }
public string Avatar { get; set; }
public string DisplayName { get; set; }
}
您正在尝试通过URI查询字符串发送模型。问题:
您的查询字符串格式不正确-应该为?Email = xxx&Password = xxx&...
您需要使用[FromUri]属性修饰postaccountmodel参数,以告知Web API绑定URI中的模型
另一种选择是将模型中的模型作为JSON或XML发送。我建议您这样做,特别是如果您确实在请求中发送密码时。(并使用SSL!)
本主题描述了Web API中的参数绑定:http : //www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句