相关疑难解决方法(0)

ASP.NET Web API - 返回CLR对象或HttpResponseMessage

对于动作方法的返回类型,Web API中的一般做法似乎是什么?

像这样返回CLR对象:

public IEnumerable<ContactModel> Get()
{
    return _contactService.GetAllForUser();
}
Run Code Online (Sandbox Code Playgroud)

或者将对象包装在HttpResponseMessage:

public HttpResponseMessage Get()
{
    IEnumerable<ContactModel> contacts = _contactService.GetAllForUser();

    return Request.CreateResponse((HttpStatusCode) 200, contacts);
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢将自己的CLR对象作为返回类型,因为它显然会产生更干净的方法,因为您不必HttpResponseMessage每次都实例化.

.net c# asp.net-web-api

15
推荐指数
2
解决办法
6610
查看次数

在mvc项目中的Apicontroller - 无法识别httppost和json方法

我有一个普通的ASP.NET MVC项目(不是Web API).在这里,我在我的控制器中创建了一个名为"api"的新文件夹,因为我想创建一个简单的api.

然后我创建以下类:

public class OfficeProductController : ApiController
{
    [HttpPost]
    public JsonResult Create(OfficeProductViewModel model)
    {
        var obj = new OfficeProductViewModel();
        return Json(obj);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里我遇到两个问题:

  • HttpPost:导致"不明确的引用"(在Http.HttpPostAttribute和Mvc.HttpPostAttribute之间)
  • Json()无法识别.它只是给了我一个"无法解决符号Json"

如果我没记错的话,这可以在web api项目中使用.

我究竟做错了什么?我需要添加什么?

asp.net-mvc asp.net-mvc-4 asp.net-apicontroller

3
推荐指数
1
解决办法
1464
查看次数