Contact Manager Web API

This sample uses ASP.NET Web API to build a simple contact manager application. The application consists of a contact manager web API that is used by an ASP.NET MVC application, a Windows Phone application, and a Windows 8 app to display and manage a list of contacts.

C# (1,9 Mo)
 
 
 
 
 
(23)
35 335 fois
Ajouter à mes Favoris
16/08/2012
E-mail del.icio.us Digg Facebook Reddit Slashdot Twitter Windows Live Favorites Windows Live Spaces
Se connecter pour poser une question


  • ASP Web Api - Routing with extension
    1 Posts | Dernier message mars 19, 2013
    • HI, I'm trying to get work my Web Api application to work with url extension (http:<url>/contacts.json like in the ContactManager sample). I put the same code in WebApiConfig.cs
      [code]
      config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json","application/json");
      config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml","application/xml");
      
      config.Routes.MapHttpRoute(
                      name:"ControllerWithExt",
                      routeTemplate:"api/{controller}.{ext}");
      
                  config.Routes.MapHttpRoute(
                      name:"IdWithExt",
                      routeTemplate:"api/{controller}/{id}.{ext}");
      [/code]
      
      But I got 404 Not found result 
      
      I try the ContactManager sample and it work fine. 
      
      The only difference between my project and the sample is the version of the packages.
      
      If someone can say me what's i'm doing wrong.
      
      Regards
  • Contact Management on windows store apps
    1 Posts | Dernier message mars 13, 2013
    • Hi ,
      
      Is contact management possible on windows store apps with XAML/C#.(I want to create a contact,delete a contact and modify a contact.). If possible how to do it.  Can u please help me on this.
      I had found only contact picker sample . 
      
      Thank u
      syamala.
  • Custom security in Web Api
    4 Posts | Dernier message janvier 10, 2013
    • I have the following scenario. My customer calls my web api service in java using POST method passing me XML structure as an input parameter. See below:
      
      <?xml version="1.0" encoding="UTF-8"?>
      <rest-client version="2.4">
      <request>
      <http-version>1.1</http-version>
      <http-follow-redirects>false</http-follow-redirects>
      <URL>http://XXXXXXXX/getCoupon.do</URL>
      <method>POST</method>
      <auth-methods>BASIC</auth-methods>
      <auth-preemptive>false</auth-preemptive>
      <auth-username>username</auth-username><auth-password>password</auth-password>
      <body content-type="application/xml" charset="UTF-8">
      &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;&lt;GetPharmacyNotesRequest&gt;
      &lt;RequestID&gt;TestRequestId1&lt;/RequestID&gt;
      &lt;DocumentID&gt;625&lt;/DocumentID&gt;&lt;/GetPharmacyNotesRequest&gt;
      </body>
      </request>
      </rest-client> 
      
      My task is to authenticate their username and password against my database before returning anything back. I have tried to figure out how to read auth-username and auth-password parameters but I came up short. Please point me in the right direction.
       
      
      Thanks
      
    • Assuming you are hosting your web API in IIS you probably want an authentication module that handles basic auth using the ASP.NET Membership provider as the identity store. We don't provide such an authentication module out of the box, but you could take a look at one implemented by the community (ex http://custombasicauth.codeplex.com/).
    • I'd suggest authenticating them once and setting a session ID that expires after a short period, and have them pass the session ID for every call they need to return data.  Store the session ID, and time and validate against that for every call.  Set it to expire, have them re-auth and repeat.
    • I've updated Daniel sample to make it work with ASP.NET Forms Auth from a web client and from the Windows Store app, here is the magic to login in AddContactsGroups method :
      
      HttpResponseMessage response = null;
                          Uri address = new Uri(@"http://localhost/");
                          CookieContainer cookieJar = new CookieContainer();
                          HttpClientHandler handler = new HttpClientHandler()
                          {
                             CookieContainer = cookieJar
                          };
                          handler.UseCookies = true;
                          handler.UseDefaultCredentials = false;
                          HttpClient client = new HttpClient(handler as HttpMessageHandler)
                          {
                              BaseAddress = address
                          };
                      
                          response = await client.GetAsync("Account/Login");
      
                          String form = await response.Content.ReadAsStringAsync();
                          int index = form.IndexOf("__RequestVerificationToken");
                          String token = form.Substring(index + 49,172);
      
                          HttpContent content = new FormUrlEncodedContent(new[]
                          {
                              new KeyValuePair<string, string>("__RequestVerificationToken", token),
                              new KeyValuePair<string, string>("UserName", "cedric"),
                              new KeyValuePair<string, string>("Password", "cyberced"),
                              new KeyValuePair<string, string>("RememberMe", "false")
                          });
                          
                          response = await client.PostAsync("Account/Login", content);
      
                          response = await client.GetAsync("api/contacts");
      
                          Contact[] contacts = await response.Content.ReadAsAsync<Contact[]>();
      
      To secure your Api Controller method just add an Authorize attribute like this :
      [Queryable]
      [Authorize(Roles = "")]
      public IEnumerable<Contact> Get()
      
      HTH
       
  • Design Question
    1 Posts | Dernier message décembre 27, 2012
    • Hi Daniel,
      
      Can you explain your thought process behind the split between the API-REST controllers for the contact logic and the more traditional MVC style controllers for the account management logic? I also noticed the views for the account logic used razor control binding while the contact logic used knockout. 
      
      Thanks,
      
      Josh
  • User Login
    1 Posts | Dernier message décembre 14, 2012
    • I have an existing database that stores all of my employees information for public viewing.  Is there a way that I can leverage LDAP login for the login form so that a user can login and update their information?
  • Update sample to RTM
    1 Posts | Dernier message décembre 05, 2012
    • Hi Daniel,
      
      After a clean install from Win 8 RTM and Visual Studio 2012 RTM the sample doesnt run. When will this be updated?
      
      Regards, Eric
  • Unable to start
    1 Posts | Dernier message octobre 10, 2012
    • When I start the app from the C# solution, it fails:
      
      Solution folders are not supported in this version of the application...".nuget" will be displayed as unavailable.
      
      Seems that there are different versions of C# express, but I'm not sure if that's the problem
  • I keep getting runtime errors when deployed in iis7
    2 Posts | Dernier message septembre 07, 2012
    • The necessary .dll files needed are there already.  How do I deploy it? Am I missing something?
    • I got it working! sorry about that.
  • Unable to access the database
    4 Posts | Dernier message septembre 07, 2012
    • Hi Daniel,
      Thanks for providing the sample. However I'm not able to get it to work even after installing SqlLocalDB.MSI and KB2544525. VS 2010 SP1 fails to load the ContactManagerContext-20120803165354.MDF and after running the web site i get the following exception in the Ajax call:
      
      {"Message":"An error has occurred.",
      "ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
      "ExceptionType":"System.InvalidOperationException",
      "StackTrace":null,
      "InnerException":{
      "Message":"An error has occurred.",
      "ExceptionMessage":"Invalid value for key 'attachdbfilename'.",
      "ExceptionType":"System.ArgumentException",
      "StackTrace":"
      <omitted>
      
      I'm running the sample on Windows Server 2008 R2 x64. Would appreciate any help to get this up and running. I'm especially looking forward to seeing how the media type formatter works since i have a similar requirement in my project.
      
      Many thanks!
      Shardul.
    • I hit the very same problem running on Windows 8 Pro. Here's the full error output:
      
      {"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.","ExceptionType":"System.Data.ProviderIncompatibleException","StackTrace":" at System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)\r\n at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)\r\n at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)\r\n at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()\r\n at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper(Object list)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at ...
    • I just found a pair of blog posts addressing this issue:
      http://blogs.msdn.com/b/sqlexpress/archive/2011/12/09/using-localdb-with-full-iis-part-1-user-profile.aspx
      http://blogs.msdn.com/b/sqlexpress/archive/2011/12/09/using-localdb-with-full-iis-part-2-instance-ownership.aspx
    • However, it seems easier to just use a local SQL Server instance if you are using full IIS.
  • Windows Store version doesn't run
    1 Posts | Dernier message août 29, 2012
    • I get the message "An issue in the ContactManager.WindowsStore.exe process caused it to fail to activate.  The process exited with a native exception.
      
      I've enabled the Nuget so it does compile just fine.
1 - 10 de 19 Articles