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

前端之家收集整理的这篇文章主要介绍了c# – 如何从IHttpActionResult方法返回自定义变量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用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,
“Date”: “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",NewCustomer);
原文链接:https://www.f2er.com/csharp/92117.html

猜你在找的C#相关文章