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

use*_*602 6 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);
}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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

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

Jas*_*sen 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 });
}
Run Code Online (Sandbox Code Playgroud)

现在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 });
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用DataContractAttributeCustomer类来控制序列化.

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

    // DataMember omitted
    public DateTime? Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后只返回创建的模型

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