如何使用ASP.NET MVC4和Web api为预定义的json结果创建客户api



在ASP.NEt MVC4应用程序中,需要创建Json Web api来服务请求可以使用URL来表示,如:

  1. http://localhost:52216/erp/api/customers退回所有客户

  2. http://localhost:52216/erp/api/customers?term=soft返回包含"soft"的客户列表。用于自动完成。

这些请求的结果必须是json对象,该对象包含单个属性,customers包含找到的customers数组。

3。向http://localhost:52216/erp/api/customers发布请求应添加请求正文中指定为json 的新客户

该方法的结果必须是json对象,该对象包含单个属性,customer包含保存的customer,但某些属性已更改。

尝试使用以下API控制器。键入浏览器http://localhost:52216/erp/api/customers返回xml格式中的错误

<Error><Message>No HTTP resource was found that matches the request URI 'http://localhost:52216/erp/api/customers'.</Message>
<MessageDetail>No action was found on the controller 'Customers' that matches the request.</MessageDetail>
</Error>

如何解决此问题?对于这样的请求,哪一种是混凝土API类的正确方法?

无法更改请求返回数据格式。类方法名称可以更改,如果需要,可以创建具有不同名称的单独方法。

using Erp.Models;
using System.Web.Http;
namespace Erp.Controllers
{
    [Authorize]
    public class CustomersController : ApiController
    {
        public object Get(string term)
        { 
            Customer[] res = CustomerRepository.GetAllOrForTerm(term);
            return new { customers = res };
        }
        public object Post([FromBody]Customer customer)
        {
            Customer res = CustomerRepository.Save(customer);
            return new { customer = res };
        }
    }
}

使用默认路由:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

更新

应用程序正在erp虚拟目录中运行,因此删除它没有帮助。

我也尝试过在浏览器

http://localhost:52216/erp/api/customers/get

http://localhost:52216/erp/api/customers/Get

但得到错误

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:52216/erp/api/customers/get'.
</Message>
<MessageDetail>
No action was found on the controller 'Customers' that matches the request.
</MessageDetail>
</Error>

以下控制器应该可以与默认路由配置一起正常工作:

public class CustomersController : ApiController
{
    // This will match GET /api/customers
    public HttpResponseMessage Get()
    {
        Customer[] res = CustomerRepository.GetAllCustomers();
        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    // This will match GET /api/customers?term=foo_bar
    public HttpResponseMessage Get(string term)
    {
        Customer[] res = CustomerRepository.GetAllOrForTerm(term);
        return Request.CreateResponse(HttpStatusCode.OK, res);
    }
    // This should match POST /api/customers
    public HttpResponseMessage Post(Customer customer)
    {
        ...
        return Request.CreateResponse(HttpStatusCode.Created, customer);
    }
}

此外,在您的代码中,您似乎用[Authorize]属性修饰了CustomersController,而没有实际解释您使用的授权机制。但无论如何,如果您正在使用授权,请确保在请求中提供有效凭据。

当你在上面的时候,签出ServiceStack作为Web API的替代方案。你会被用.NET编写RESTful web服务容易得多所吸引。在web API v2中,他们引入了基于属性的路由(简化了路由),向ServiceStack又迈进了一步,但他们还有另一步要做,那就是基于消息的服务。那么Web API将真正有用。在他们完成最后一步之前,我个人将继续使用ServiceStack,它提供了编写RESTfule服务的简单性。

最新更新