Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 如何使用EFCodeFirst为MVC应用程序设置DAL RESTful服务?_Asp.net Mvc 3_Model_Asp.net 4.0_Data Access Layer_Wcf Rest - Fatal编程技术网

Asp.net mvc 3 如何使用EFCodeFirst为MVC应用程序设置DAL RESTful服务?

Asp.net mvc 3 如何使用EFCodeFirst为MVC应用程序设置DAL RESTful服务?,asp.net-mvc-3,model,asp.net-4.0,data-access-layer,wcf-rest,Asp.net Mvc 3,Model,Asp.net 4.0,Data Access Layer,Wcf Rest,对于MVC3应用程序,我想创建一个可重用的DAL,作为服务访问,因为这将在将来用于其他项目 我首先在一个单独的项目中使用TT模板和EFCODE,然后在RESTful WCF服务中使用它 此服务的结构似乎有点不同于我编写的其他WCF服务,在这些服务中,我将RESTful签名和可选JSON响应指定为服务接口中的方法装饰器,即: [WebGet(UriTemplate = "GetCollection")] public List<SampleItem> GetCollec

对于MVC3应用程序,我想创建一个可重用的DAL,作为服务访问,因为这将在将来用于其他项目

我首先在一个单独的项目中使用TT模板和EFCODE,然后在RESTful WCF服务中使用它

此服务的结构似乎有点不同于我编写的其他WCF服务,在这些服务中,我将RESTful签名和可选JSON响应指定为服务接口中的方法装饰器,即:

    [WebGet(UriTemplate = "GetCollection")]
    public List<SampleItem> GetCollection()
    {
        // TODO: Replace the current implementation to return a collection of SampleItem instances
        return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
    }

    [WebInvoke(UriTemplate = "", Method = "POST")]
    public SampleItem Create(SampleItem instance)
    {
        // TODO: Add the new instance of SampleItem to the collection
        throw new NotImplementedException();
    }
[WebGet(UriTemplate=“GetCollection”)]
公共列表GetCollection()
{
//TODO:替换当前实现以返回SampleItem实例的集合
返回new List(){new SampleItem(){Id=1,StringValue=“Hello”};
}
[WebInvoke(UriTemplate=”,Method=“POST”)]
公共SampleItem创建(SampleItem实例)
{
//TODO:将SampleItem的新实例添加到集合中
抛出新的NotImplementedException();
}
这个RESTful WCF服务(从RESTful WCF选项创建)的不同之处在于没有接口,我可以用我需要的来装饰服务方法——这很好。该服务将公开GetUserByID(intid)等方法

问题是,我想在MVC3应用程序中使用它,但不清楚如何将模型连接到我的服务,并且希望了解实现这一点的一些方向


谢谢。

考虑到这一点,你的MVC应用程序现在只知道你的服务。它不知道它背后有一个DAL。基本上,考虑服务的“持久性”层。因此,现在您的MVC模型必须使用服务填充自身。所以,就像任何其他应用程序填充服务一样,这就是模型填充自身的方式。然后,控制器将使用模型返回视图


这并不是你想要的实质,但是关于如何使用.NET中的RESTful服务,有很多资源。检查这些并让它们填充您的模型。然后将您的模型放到视图中。

假设您要公开一个名为Person的实体。WCF REST服务可能如下所示:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]    
public partial class PeopleWebService
{
    [WebGet(UriTemplate = "")]
    public List<Person> GetCollection()
    {
        try
        {
            IPeopleRepository repository = ServiceLocator.GetInstance<IPeopleRepository>();
            var people = repository.GetPeople();
            // use automapper to map entities to Person resource
            var result = Mapper.Map<List<Person>>(people);
            return result;
        }
        catch (Exception exception)
        {
            // do logging etc
            throw new WebFaultException(HttpStatusCode.InternalError);
        }
    }

    /* other methods */
}
[DataContract]
public class Person
{
    [DataMember]
    public string GivenName { get; set; }

    / * more properties */
}
使用T4生成这些数据可能也是一件好事。路由定义如下:

public void Register(RouteCollection routes)
{
    routes.AddService<WorkspaceWebService>("api/v1/people");
}
公共作废登记簿(路由收集路由)
{
routes.AddService(“api/v1/people”);
}
要从ASP.NET MVC项目中使用它,您可以将上面定义的资源(又名Person)作为程序集共享,或者您可以使用T4生成一组单独的资源,这些资源几乎相同,但ASP.NET MVC需要一些附加属性,如用于验证的属性。我会生成它,因为我的ASP.NETMVC视图模型通常独立于我的REST资源进行演化

假设您的REST服务在运行,而您的MVC网站在运行。您的PeopleController可能如下所示

public class PeopleController : ControllerBase
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(Get<List<Person>>(new Uri("https://api.example.com/api/v1/people")));
    }

    protected T Get<T>(Uri uri)
    {
        var request = (HttpWebRequest) WebRequest.Create(uri);
        request.Method = "GET";
        request.ContentType = "text/xml";
        using (var response = (HttpWebResponse) request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                Debug.Assert(responseStream != null, "responseStream != null");
                var serializer = new DataContractSerializer(typeof (T));
                return (T) serializer.ReadObject(responseStream);
            }
        }
    }
}
公共类PeopleController:ControllerBase
{
[HttpGet]
公共行动结果索引()
{
返回视图(获取新Uri(“https://api.example.com/api/v1/people")));
}
受保护的T获取(Uri)
{
var request=(HttpWebRequest)WebRequest.Create(uri);
request.Method=“GET”;
request.ContentType=“text/xml”;
使用(var response=(HttpWebResponse)request.GetResponse())
{
使用(var responseStream=response.GetResponseStream())
{
Assert(responseStream!=null,“responseStream!=null”);
var serializer=新的DataContractSerializer(typeof(T));
return(T)serializer.ReadObject(responseStream);
}
}
}
}
根据您的问题,我假设您想要使用JSON。为此,您只需在请求上设置适当的ContentType,并使用DataContractJsonSerializer而不是DataContractSerializer。请注意,日期和DataContractJsonSerializer存在一些问题。如果contenttype为“text/XML”,WCF rest服务将自动返回XML,如果contenttype为“application/JSON”,则返回JSON


请注意,MVC应用程序不了解数据库、数据库实体或其数据库上下文。事实上,MVC应用程序中没有数据库逻辑。您必须密切关注安全性,因为WCF rest服务中缺少用户上下文。但是,这是一个完全不同的讨论。

我刚刚重读了你的帖子,意识到你所创建的服务缺少一个接口。这应该是你问题的关键。我的观点仍然是,你需要关注问题的“填充我的模型”部分,而不是问题的MVC部分。这验证了我上周的发现,因为这可能不是最好的方法。在使用WCF RESTful模板时,您必须为数据序列化添加额外的代码,即使它是纯.Net应用程序。后来我意识到,我从来都不想从客户端(以任何方式)直接访问DAL。然而,未来的项目可能需要这种灵活性。非常好地解释了序列化过程。谢谢。您可以使用WCF自动执行中概述的所有序列化等操作。但是,您在客户端上失去了很多功能,尤其是在处理错误时。