加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:18:57 所属栏目:百科 来源:网络整理
导读:我试图用Ihttpstatus标头获取此 JSON响应,该标头声明代码201并保持IHttpActionResult作为我的方法返回类型. 我想要的JSON返回: {“CustomerID”: 324} 我的方法: [Route("api/createcustomer")][HttpPost][ResponseType(typeof(Customer))]public IHttpAct
我试图用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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读