如何从HttpActionResult Ok方法(Web Api)获取对象? [英] How to get the object from HttpActionResult Ok method (Web Api)?

查看:48
本文介绍了如何从HttpActionResult Ok方法(Web Api)获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习一些Web Api基础知识,我想通过 Ok(object)返回并传递一个对象.像这样:

I'm learning some Web Api basics and I want to return and pass an object by Ok(object). Something like this:

[HttpGet]
public IHttpActionResult Get()
{
    var someString = "";
    return Ok(someString);
}

现在,我想测试此方法,并断言从此Get()方法返回的字符串是否与预期的相同.我猜会看起来像这样:

Now I want to test this method and to assert if the returned string from this Get() method is the same as expected. I Guess will look something like this:

[TestMethod]
public void TestGet()
{
    IHttpActionResult result = controller.Get();
    Assert.AreEqual("", result.??);
}

我看到了问题,但最好的答案是解释如何验证 HttpStatusCode ,而不是传递的对象.

I saw this question but the best answer is explaining how to validate the HttpStatusCode, not the passed object.

推荐答案

您可以通过将结果转换为 OkNegotiatedContentResult< string> 并访问其 Content 来访问返回的字符串.属性.

You can access the returned string by casting the result to OkNegotiatedContentResult<string> and accessing its Content property.

[TestMethod]
public void TestGet()
{
    IHttpActionResult actionResult = controller.Get();
    var contentResult = actionResult as OkNegotiatedContentResult<string>;
    Assert.AreEqual("", contentResult.Content);
}

来自以下示例代码: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆