.net - 在 web api 上接收时属性为 null

标签 .net asp.net-mvc json web-services asp.net-web-api

我的 web api 中有以下方法

public class AccessPanelController : ApiController
    {
        public HttpResponseMessage PostGrantAccess([FromUri]GrantAccessRequest grantAccessRequest)
        {
            var deviceId = grantAccessRequest.DeviceId;

            var grantAccessResponse = new GrantAccessResponse()
                {
                    Status = "OK"
                };
            var response = Request.CreateResponse<GrantAccessResponse>(HttpStatusCode.OK, grantAccessResponse);
            return response;
        }

    }

GrantAccessRequest 类:
public class GrantAccessRequest
{
    public string DeviceId { get; set; }
}

客户:
  HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:55208/");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            Uri uri = null;

            var request = new GrantAccessRequest { DeviceId = "bla" };
            var response = client.PostAsJsonAsync("api/accesspanel", uri).Result;
            if (response.IsSuccessStatusCode)
            {
                uri = response.Headers.Location;
            }

在我的 PostGrantAccess方法,grantAccessRequest已构建,但 DeviceId一片空白

最佳答案

摆脱[FromUri] Controller Action 的属性。同样在客户端上,您似乎没有对 request 做任何事情。包含有效负载的变量:

public HttpResponseMessage PostGrantAccess(GrantAccessRequest grantAccessRequest)

为了更好地理解模型绑定(bind)在 Web API 中的工作原理,我建议您阅读 following article .

所以:
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:55208/");

    var request = new GrantAccessRequest { DeviceId = "bla" };
    var response = client.PostAsJsonAsync("api/accesspanel", request).Result;
    if (response.IsSuccessStatusCode)
    {
        var uri = response.Headers.Location;
    }
}

请注意,您不需要设置 Accept在这种情况下请求 header ,因为您使用的是 PostAsJsonAsync方法。

另外我不知道这是否是您的问题中的错字,但您似乎已指定 api/accesspanel作为 url,而您的 Controller 操作称为 GrantAccessRequest .

关于.net - 在 web api 上接收时属性为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15340131/

相关文章:

asp.net-mvc - Asp.Net MVC - 进修类(class)

asp.net - 为什么我的 asp 登录标签中的第一个字符是斜体?

c# - 如何对 ArrayList(int) 进行排序

c# - 将 UserControl 转换为自定义控件

c# - MVC 4.5.2 Response.WriteFile 大于 2gb

asp.net-mvc - .net mvc 仅在具有值时才在 View 中显示字段

json - Go:检测无效 JSON 字符串字符的最佳方法是什么?

php - 比较产品 php 脚本

java - org.springframework.web.client.RestClientException : Could not extract response:

c# - 如何使用 Azure Active Directory .NET SDK 删除 AppRoleAssignment?