簡體   English   中英

如何從IHttpActionResult方法返回自定義變量?

[英]How to return from an IHttpActionResult method a custom variable?

我試圖用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 });
}

這會得到你的結果:

[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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM