如何从IHttpActionResult方法返回自定义变量?

时间:2014-06-19 00:53:07

标签: c# json asp.net-web-api2

我正在尝试使用Ihttpstatus标头获取此JSON响应,该标头声明代码201并将IHttpActionResult保留为我的方法返回类型。

我想要的JSON返回:

  

{“CustomerID”:324}

我的方法:

[Route("api/createcustomer")]
[HttpPost]
[ResponseType(typeof(Customer))]
public IHttpActionResult CreateCustomer()
{
    Customer NewCustomer = CustomerRepository.Add();
    return CreatedAtRoute<Customer>("DefaultApi", new controller="customercontroller", CustomerID = NewCustomer.ID }, NewCustomer);
}

JSON返回:

  

“ID”:324,   “日期”:“2014-06-18T17:35:07.8095813-07:00”,

以下是我尝试过的一些回复,或者给了我uri null错误,或者给了我类似于上面示例的回复。

return Created<Customer>(Request.RequestUri + NewCustomer.ID.ToString(), NewCustomer.ID.ToString());
return CreatedAtRoute<Customer>("DefaultApi", new { CustomerID = NewCustomer.ID }, NewCustomer);

使用httpresponsemessage类型方法,可以解决此问题,如下所示。但是我想使用IHttpActionResult:

public HttpResponseMessage CreateCustomer()
{
    Customer NewCustomer = CustomerRepository.Add();
    return Request.CreateResponse(HttpStatusCode.Created, new { CustomerID = NewCustomer.ID });
}

1 个答案:

答案 0 :(得分:10)

这将为您提供结果:

[Route("api/createcustomer")]
[HttpPost]
//[ResponseType(typeof(Customer))]
public IHttpActionResult CreateCustomer()
{
    ...
    string location = Request.RequestUri + "/" + NewCustomer.ID.ToString();
    return Created(location, new { CustomerId = NewCustomer.ID });
}

现在ResponseType不匹配。如果您需要此属性,则需要创建新的返回类型,而不是使用匿名类型。

public class CreatedCustomerResponse
{
    public int CustomerId { get; set; }
}

[Route("api/createcustomer")]
[HttpPost]
[ResponseType(typeof(CreatedCustomerResponse))]
public IHttpActionResult CreateCustomer()
{
    ...
    string location = Request.RequestUri + "/" + NewCustomer.ID.ToString();
    return Created(location, new CreatedCustomerResponse { CustomerId = NewCustomer.ID });
}

另一种方法是使用Customer类上的DataContractAttribute来控制序列化。

[DataContract(Name="Customer")]
public class Customer
{
    [DataMember(Name="CustomerId")]
    public int ID { get; set; }

    // DataMember omitted
    public DateTime? Date { get; set; }
}

然后只返回创建的模型

return Created(location, NewCustomer);
// or
return CreatedAtRoute<Customer>("DefaultApi", new controller="customercontroller", CustomerID = NewCustomer.ID }, NewCustomer);