FAQ Database Discussion Community
c#,asynchronous,asp.net-web-api2,autofac
I have a fairly controller that requires login in before being able to do any other calls. I have an authorization filter setup to deny access to method without being authenticated, but I'm trying to setup an override for the login method. The issue is that the controller is using...
c#,asp.net-mvc,entity-framework,asp.net-web-api,asp.net-web-api2
I've got an entity which I pull directly from the database using EF that looks like this: public class MyEntity : EntityBase { public string MyProperty { get; set; } } where as EntityBase looks like the following public abstract class EntityBase { public int Id { get; protected set;...
visual-studio-2012,visual-studio-2013,asp.net-web-api2,iis-express,authorize-attribute
The exact, precise, .sln file which contains my MVC 5/ Web Api 2 web project behaves one way when I run it from the Visual Studio 2012 installation and behaves in an entirely different way when I run it from Visual Studio 2013. In particular, I have a CustomerController that...
c#,json,serialization,asp.net-web-api2
I want to send parameter-settings from a backendapplication to the frontend. I also need to be able to have different type of parameters (Portnumbers, folders, static strings and such). So I've designed a baseclass, Parameter as such: public abstract class Parameter { public abstract bool isValid(); } Let's say that...
routes,asp.net-web-api2
I've used the selected answer from here: Routing based on query string parameter name to build my routes but they don't work as expected: my route: config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}", defaults: new { controller = "Products" } ); my actions: public string GetProductById(int id) {} public string GetProductByIsbn(string isbn)...
unit-testing,c#-4.0,asp.net-web-api2,mstest,anonymous-types
I have been tasked with writing a unit test for the following Web API 2 action: public HttpResponseMessage Get() { IEnumerable<KeyValuePair<long, string>> things = _service.GetSomething(); return ActionContext.Request.CreateResponse(things.Select(x => new { Thing1 = x.Prop1.ToString(), Thing2 = x.Prop2 }).ToArray()); } I am testing the status code and that works fine, but I...
c#,asp.net-web-api,json.net,asp.net-web-api2
I made a simple JsonConverter because I have a page that posts a JSON array which can be of a generic type. Posting JSON data and converting that to a typed object works fine using the overriden ReadJson method in my custom JsonConverter class. I also need to read from...
data-annotations,asp.net-web-api2,circular-reference,ef-database-first
I'm trying to specify a subset of data to be returned from a database query by Web API 2. In particular, for this query, I first turn lazy loading on: db.Configuration.LazyLoadingEnabled = true; This is because there are potentially infinite levels of children. For example: Parent: {"name":"Jon","children":[{"name":"Dave","children":["name":"Ed"... Each person in...
c#,web-api,asp.net-web-api2,autofac,ioc-container
I have a custom DelegatingHandler in a class library that I need to register with Autofac. The webapi host resolves it's dependencies on runtime, so the host has no references to this library. public class LocalizationHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken ) {}...
c#,design-patterns,architecture,asp.net-web-api2,simple-injector
I have an Asp.net WebApi Project and i am using Simple Injector for dependency injection. I have some messages, message handlers , decorators on my project. I am using decorator pattern. I need to keep details of each process and i need to save them to database.For example, i want...
asp.net-web-api,asp.net-web-api2
There seems to be two functionally different ways to enable cross-origin request sharing in Web API 2. One is to import System.Web.Http.Cors, decorate a controller with the EnableCors attribute and to write config.EnableCors() in the WebApiConfig: [EnableCors(origins: "http://111.111.111.111", headers: "*", methods: "*")] public class GenericController : ApiController { // etc....
c#,json,json.net,asp.net-web-api2,custom-attributes
I'm rolling my own ValidateAntiForgeryToken attribute for Web API 2.2 for one of my controllers that processes form data through AJAX calls. I'm sending the data to my controller as JSON and it looks like this (pulled from Fiddler): {"__RequestVerificationToken":"E8EoBCaFbqSOXhQZiuM93jciTcOAYeLjZj682-3SZRaQ6OOtrm-caZI_IWnX1FH_nwe_AuWnWwxy5ulS0Ynz0STlNptqN09Lu69HxyTeA9PUln8h73yjahB24QPxqI010","ProjectInfo.Description":"Test Description 2"} I was trying to get the __RequestVerificationToken data...
asp.net-mvc-routing,asp.net-web-api2
I have a web api with the following routes: routes.MapHttpRoute( name: "DefaultGet", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Home", id = RouteParameter.Optional } ); routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional } ); These are two Actions inside a...
c#,.net,unit-testing,asp.net-web-api,asp.net-web-api2
I have a Web API 2 controller which has an action method like this: public async Task<IHttpActionResult> Foo(int id) { var foo = await _repository.GetFooAsync(id); return foo == null ? (IHttpActionResult)NotFound() : new CssResult(foo.Css); } Where CssResult is defined as: public class CssResult : IHttpActionResult { private readonly string _content;...
asp.net,asp.net-mvc,asp.net-web-api,asp.net-web-api2,model-binding
I have a PUT method in web api which accepts a JSON data and a route data as follows. [Route("api/v1/Orders/{orderId}/active")] public HttpResponseMessage Put(Guid? orderId,List<ActiveRequest> activeRequests) { } public class ActiveRequest { public int Id { get; set; } public bool IsActive { get; set; } } Now is it possible...
c#,asp.net-web-api,dependency-injection,unity,asp.net-web-api2
I have a complex type to inject into a webapi controller and I am unable to resolve this dependency public class MyController(IMyComplexType) The implementation of IMyComplexType has at least 5 dependencies I1, ... I5(so its implementation recieve I1...I5) I have a Bootstrapper class to Register all dependencies, below a snippet...
c#,asp.net-web-api,asp.net-web-api2
After several hours of googling and attempting to figure this out, I still can't figure this out. The issue is that the "[FromBody] Route input" parameter for the create method will for some reason bind Route.RouteMember[0].Lab to the provided data, but it will set Route.RouteMember[0].RouteMemberType to null. (This will happen...
.net,datetime,asp.net-web-api2,asp.net-web-api-odata
Application is running on localhost. Server is one hour earlier than client! Client sends time : Sat Apr 25 2015 00:00:00 GMT-0400 (Eastern Daylight Time) Request is sent: dateOfArrival: "2015-04-25T04:00:00.000Z" Server receives time: {4/24/2015 11:00:00 PM} Why is there one hour difference between and how can I handle it? I...
javascript,c#,.net,json,asp.net-web-api2
I am using MS Web API 2 to receive calls from our web page using ajax. Then I have 2 classes: subscriber and externalSubscriber. Subscriber contains very basic data like a name and id. External subscriber inherits from subscriber and adds basic data like address and email. I have one...
odata,breeze,asp.net-web-api2,single-page-application,azure-active-directory
I am having two web applications, one a SPA using AngularJS + BreezeJS and the other a WebAPI. We are building authorization in the WebAPI and the results get filtered based on user access. We want the user to sign-in into organization Azure AD in the SPA and pass the...
java,c#,android,asp.net-web-api,asp.net-web-api2
How can I convert C#'s DateTime format from gson to Java Date? In gson which setDateFormat is correct? C# DateTime time = DateTime.Now; JSON { "date_time": "2015-04-24T09:22:08.6964069+08:00" } Android private Date date_time; Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); gson.fromJson(resultString, objectClass); E/AndroidRuntime(24671): Caused by: com.google.gson.JsonSyntaxException: 2015-04-24T16:20:08.3672729+08:00 E/AndroidRuntime(24671): Caused by: java.text.ParseException: Unparseable date:...
c#,asp.net-web-api,asp.net-web-api2
I am currently playing around with some things...According to this link, I need to construct a route that is open to the following format webServiceURL/version/devices/deviceLibraryIdentifier/registrations/passTypeIdentifier?passesUpdatedSince=tag so I defined the route like so config.Routes.MapHttpRoute( name: "DefaultApi3", routeTemplate: "{version}/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{passesUpdatedSince}", defaults: new { controller = "SerialNumbers", action = "GET", passesUpdatedSince =...
c#,.net,asp.net-web-api,asp.net-web-api2,owin
I started using Owin self host for my API and now I'm trying to fix some tests, which started to fail, because Owin does not support HttpContext.Current Now I'm stuck in getting HttpRequestBase from IOwinContext. Here's my old code, which I used before Owin: public static HttpRequestBase GetRequestBase(this HttpRequestMessage request)...
asp.net-mvc,asp.net-web-api,wildcard,asp.net-web-api2
I'm wanting to use webapi 2 inside an MVC5 project (AngularJS, not that this should make any difference) to create the following types of routes GET api/animals/cats => return cats GET api/animals/dogs => return dogs GET api/animals/* => return all animals (e.g. cats+dogs) Background: What I did to get started...
json,entity-framework,repository-pattern,asp.net-web-api2,poco
I am working on a large application being developed using Repository Pattern, Web APIs, AngularJS. In one of the scenario, I am trying to retrieve data from a single lead which has relations with approx. 20 tables. Lazy loading is disable, so I am using Include to get the data...
c#,web-api,asp.net-web-api2
Iām writing a custom WebApi Authorization filter. I need to read the securitySqlConnectionString back from the actionContext variable. To do this, I need to perform a cast (e.g. as I have attempted using TransactionRequestBundle<SearchDefault>), however, the problem is that in TransactionRequestBundle<T>, T will vary, hence the cast below will only...
c#,asp.net,azure,asp.net-web-api2
I have a Web API 2 project with help pages that runs fine locally but throws this error when I push it to Azure: Method not found: 'System.String System.String.Format (System.IFormatProvider, System.String, System.Object) I temporarily turned custom errors off so full stack trace can be seen here The error is originating...
rest,asp.net-web-api,asp.net-web-api2,asp.net-web-api-routing
I've got a VendorsController that supports GET (by id) and POST (with a model). They are working as expected when called through the intended routes. However, I noticed that if I add an id to the POST route (ie add "/5" to "api/vendors"), I get a 405, with Response Body...
.net,ninject,asp.net-web-api2
I've removed Unity and am now attempting to use Ninject in its place. For the most part it works, however I cannot get it to play nice with Web API 2. I have a NinjectWebCommon.cs file (which I have not changed aside from adding some registrations which work fine if...
asp.net-web-api,asp.net-web-api2
I have this function: protected void Application_Start() { Database.SetInitializer(new PersonDbInitializer()); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); } The WebApiConfig is: public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }...
entity-framework,odata,web-api,asp.net-web-api2
I have got two models. A Product model: public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public virtual ICollection<Categories> Categories { get; set; } } And a Categories model: public class Categories {...
c#,asp.net,azure,memory,asp.net-web-api2
How do Azure websites scale out? I'm interested in memory: is it global for all copies of websites or does each copy have its own memory? If I scale out my websites, can my memory cache be cleared by every copy, or do I need to clear it from every...
ios,html5-video,mobile-safari,asp.net-web-api2
I'm using WebApi to serve videos on a website. I've tested this on all major desktop browsers and the HTML5 Video tag plays the video as expected. However, I can't get this to work on iPhones (Mobile Safari). The Get() method is never called even after pressing the play button....
asp.net-mvc-5,entity-framework-6,asp.net-web-api2,structuremap
I have a Mvc5-WebApi2 application that uses StructureMap for dependency injection using the StructureMap.Mvc5 and StructureMap.WebApi2 Nuget packages. I want to register my EF 6 DbContext with HttpContext lifecycle for both MVC and Web controllers. Can someone point me to a succinct explanation on how to achieve this for both...
c#,odata,asp.net-web-api2
I'm trying to create an ODataController that supports casting action. Let's say we have Shape class and Circle class that derives from Shape namespace NS { public abstract class Shape { int Id; int X; int Y; } public class Circle : Shape { int Radius; } } And I...
c#,json,asp.net-web-api2
This my client code var sayeed = { firstname: "Sayeed", surname: "Alquiaty" }; alert(JSON.stringify({ person: sayeed })); $.ajax({ url: "api/parent", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify({ person: sayeed }), success: function(response) { response ? alert("It worked!") : alert("It didn't work."); } }); At the Server side public class Person...
attributes,asp.net-web-api2,swagger,swagger-ui,swashbuckle
Is it possible to leverage MultipleApiVersions in Swagger UI / Swashbuckle when using attribute routing? Specifically, I implemented versioning by: using System.Web.Http; namespace RESTServices.Controllers.v1 { [Route("api/v1/Test")] public class TestV1Controller : ApiController { ... } Version 2 would be in a v2 namespace. In a controller named TestV2Controller. The route would...
c#,asp.net,asp.net-web-api2
I have a web api that is working great in test using an access token / bearer authentication. I authenticate and make requests using HttpClient. Easy. Here is the basic web client setup. The base address is a constant that I change when moving to production. public static HttpClient GetClient()...
entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2
I am using web api 2, and entity framework 6. I have created an async web api, which updates all the records at once. I am also using Autofac for dependency injection. My service interface is as follows : Task<Approval> TakeAction(int id, bool isApprove) void TakeAction(bool isApprove) These are my...
c#,asp.net,asp.net-mvc,asp.net-web-api2
public override void OnException( System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Exception != null) Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception); base.OnException(actionExecutedContext); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(actionExecutedContext.Exception.Message), ReasonPhrase = "Deadly Exception", }); } This is my filter for Model passed to any asp.net web api. It...
web-api,asp.net-web-api2,azure-documentdb
I am using Azure Document DB and can successfully create an object using the code below. However I am not able to return the created object back to the client. Despite the code hitting the line return Ok(doc); the response seen in both Fiddler and Postman is always empty. Controller...
c#,asp.net,entity-framework-6,asp.net-web-api2
I'm using ASP.NET WebApi 2 and loading in part of a relational database structure into the front end website. This allows the user to make changes to multiple tables in a single store and to also view some extra data. This mostly works pretty well. It means I can store...
c#,iis,file-upload,asp.net-web-api2
The below code works very well on development environment VS 2012, the images are saved to App_Data. When I deployed the same on Win 8.1, IIS 8.5, the App_Data was missing. I manually create the folder and set the properties as given in http://hintdesk.com/tutorial-publish-asp-net-web-api-in-iis-8-5-and-windows-8-1/. I am seeing strange behavior as...
c#,asp.net,.net,asp.net-web-api,asp.net-web-api2
The configuration has nothing to do with the error This is my configuration for the Web API in App_Start/WebApiConfig.cs: public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );..... And this is my global.asax class: GlobalConfiguration.Configure(WebApiConfig.Register);...
angularjs,rest,asp.net-web-api2,ngresource
I have this controller: public class SeguiAttivazioneController : ApiController { [HttpGet] public IHttpActionResult DoWork1() { ... return Ok(); } [HttpGet] public IHttpActionResult DoWork2() { ... return Ok(); } [HttpGet] //I would like to have a search with GET verb, but I cannot validate my ModelState with dataAnnotation public IHttpActionResult AnotherSearch(string...
asp.net-web-api,asp.net-web-api2
In Asp.net Web Api, I want to control, request "access token" key is (which is in request header) valid or not. But I cound't decide where should I implement this kind of control. ActionFilter or controller constructor etc. etc.
c#,angularjs,asp.net-web-api2
The problem is, when the method is entered, "session" is a null. As you can see, headers and JSON-object are correct. Could you tell me what I'm doing wrong? My POST-request with angular: $scope.send = function () { var data = { "session": session }; var req = { method:...
c#,odata,asp.net-web-api2,owin,self-host
I'm building an OWIN self-hosted Web API 2 service. I need for this service to expose OData end points. The traditional IIS-hosted method involves App_Start/WebApiConfig.cs: using ProductService.Models; using System.Web.OData.Builder; using System.Web.OData.Extensions; public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code: ODataModelBuilder builder = new ODataConventionModelBuilder();...
async-await,asp.net-web-api2
Using Web API 2, I have a process that generates a temporary file for the purpose of writing it to the output stream for client consumption. The process can be somewhat long running, taking a few minutes to complete. What I'd like to do is serve the file asynchronously and...
c#,asp.net-web-api,asp.net-web-api2
I have 2 asp.net web api actions in an ApiController-subclassed controller. The 2 action methods are POST. One method is working with non-null request body. But the other action method always get null request body. I do not know the reason why the second POST action does not work. Please...
asp.net-web-api,routes,asp.net-web-api2,asp.net-web-api-routing,attributerouting
I am using Routing Attribute to try to send a string via url to my web Api. I have a Route defined as [Route("Search/{searchText}")] I am expecting a string value as searchText. It seems to be working fine but I am getting an error if there is a '.' in...
c#,http,webclient,asp.net-web-api2,httpresponse
How do I get Content-Disposition parameters I returned from WebAPI controller using WebClient? WebApi Controller [Route("api/bla/bla/bla")] public HttpResponseMessage GetFile(int fileId) { try { var file = GetSomeFile(fileId) HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(new MemoryStream(file)); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName =...
c#,oauth-2.0,asp.net-web-api2
Hi I am using Bearer authentication in my web api 2. After user login i generate access token to the user. Further when they request my web api, they have to send access token in request header. All valid access tokens are requesting web api with out any problem. But...
asp.net,.net-4.5,asp.net-web-api2
So lets say we have three environment dev, qa and prod. In addition to that, all developers have their own environment. How do you manage connection string or app setting for each env? I believe for dev, qa and prod i can use web.config transformations (lot of resources online on...
c#,asp.net,.net,automapper,asp.net-web-api2
So I have this WebApiPrice.Web.Api.Models.Category class /* * Service model class, that will represent categories */ using System; using System.Collections.Generic; namespace WebApiPrice.Web.Api.Models { public class Category { private List<Link> _links; public long CategoryId { get; set; } public string Name { get; set; } public DateTime Timestamp { get; set;...
.net,asp.net-web-api2
So I know that you can create controller method that is only accesible if user is authenticated and has some role for example: [Authorize(Roles="Admin")] adding this before controller method would make that method available only for user that has a role of Admin I am wondering if it is possible...
angularjs,xss,asp.net-web-api2,antixsslibrary
I have a web application. I am using Angularjs and Web Api2. I have a simple form where user can insert some free text that will be send via email to other people. The text is also saved on db and later can be shown in a web site page....
c#,json,asp.net-web-api2
I am using two POCO classes: public class GearModel { public long Id { get; set; } public Int16 LocationNumber { get; set; } public string HooksPerRod { get; set; } public string TerminalWeightBait { get; set; } public string TerminalWeight { get; set; } public FlyModel Shrimps { get;...
c#,asp.net,exception-handling,asp.net-web-api2,httpresponse
I have seen examples like this public IHttpActionResult GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Ok(item); } But I have also imagine this is an option public IHttpActionResult GetProduct(int id) { Product item = repository.Get(id); if (item == null) {...
odata,asp.net-web-api2,simple.odata
I get error "The parameter 'wheels' is of Edm type kind 'Collection'. You cannot call CreateCollectionWriter on a parameter that is not of Edm type kind 'Collection'." Below are details of my setup: Web API 2.2 OData v4 service : I have defined Action in WheelsController class in my...
rest,asp.net-web-api,timezone,json.net,asp.net-web-api2
Is there any ISO standard for how we should return a timezone in a REST API? If I return a TimeZone type from a ASP.NET WebApi 2 action, the framework serialises the response model to look like this: { "Id": "Dateline Standard Time", "DisplayName": "(UTC-12:00) International Date Line West", "StandardName":...
angularjs,odata,asp.net-web-api2
I'm following damienbod's series on webapi and odata4 where the odata url to query a single product would be: http://localhost/odata/Products(5) The question is, how do I structure my $resource url in angular to map to this url? I've tried return $resource(appSettings.serverPath + "/odata/Products(:id)" but this breaks when I want to...
odata,asp.net-web-api2
I'm building an OData response by throwing a standard HttpResponseException. The exception itself is built with an HttpResponseMessage based on ODataError. new ODataError() { ErrorCode = code, Message = message, InnerError = new ODataInnerError() { Message = innerException.Message, StackTrace = innerException.StackTrace, TypeName = innerException.GetType().Name }, InstanceAnnotations = annotations }); The...
c#,asp.net,visual-studio-2013,asp.net-web-api2
I was following along the following tutorial by Microsoft on ASP.net and WebApi: Working With Data Tutorial Over in this example, two separate models were created: one for Authors and one for Books. When a booked is stored in a database, an author id is stored along with it as...
javascript,c#,asp.net-web-api2
I have a Web API 2 controller. I am sending a JavaScript Object from the client in a call: myObject = {propertyOne: 'Hi', propertyTwo: 'Bye'} Do I HAVE to make a class with those properties in C# to receive the object as an argument to the Web API controller? public...
angularjs,asp.net-web-api2,angularjs-routing,asp.net-web-api-routing
I am using Angular Routing with a webapi 2 controller. Although the default path loads with the correct data, when I click on an item in a list containing a link to a details page, no data is loaded. The browser shows what I believe to be the correct url...
asp.net-mvc,entity-framework,asp.net-mvc-5,web-api,asp.net-web-api2
I'm developing an ASP.Net MVC 5 application with Web API 2 and Entity Framework. I have created a WEB API 2 Controller with actions, using Entity Framework named EmployeeAPIController and consuming the API using ajax call as shown below. function loadEmployees() { alert("In Load"); $.ajax({ type: "GET", url: "/api/EmployeeAPI", success:...
c#,windows-phone-8.1,json.net,asp.net-web-api2
I'm working with twitch REST API for education purposes(MVVM pattern) on Windows Phone platform. I noticed pure performance while using HttpClient: I get a collection of 10 elements Pass it to CheckCannelStreamStatus I removed the code because it was draft for prototype. Like in the answer bellow the problem is...
asp.net,asp.net-web-api2,asp.net-identity-2
I have some problems with adopt Web API 2 Identity. In project. I add StartUp.cs Like this: using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(MyNamespace.Startup))] namespace MyNamespace { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } } After that I add partial class for enable Token authorization:...
c#,wcf,odata,asp.net-web-api2
I'm trying create a OData service using Webapi 2. I've already created a working example that works with a local context. Now, I want to use a Context Provided from a seperate WCF Service. WebApiConfig.cs: public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id...
odata,asp.net-web-api2,firewall,nat,portforwarding
I have two applications hosted on different computers : An OData web site APP1 on PC1 A basic MVC application APP2 on PC2 My router (my.server.com) is configured to forward following request : *:10080 to PC1:80 *:20080 to PC2:80 I used Microsoft.OData.Client library to generate OData context and use it...
c#,linq,lambda,asp.net-web-api2
I need search max and min value using linq and lambda. I have sql select, for example: SELECT [ProdID] ,min([APY]) as minAPY ,max([APY]) as minAPY FROM [dbase].[dbo].[Dept] group by ProdID order by ProdID Thanks for help me!...
c#,asp.net,asp.net-web-api,web-api,asp.net-web-api2
I have two different model need to be passed to web api. those two sample model are as follow public class Authetication { public string appID { get; set; } } public class patientRequest { public string str1 { get; set; } } so to get work this i have...
angularjs,angular-ui-router,asp.net-web-api2
Until the end of my Angular application development period, I worked with two seperate projects. WebApi and Angular SPA. Now I am trying to deploy them to our production server and because of the need for seperate SSL certificates, we decided to combine them and run in the same Project....
sockets,azure,asp.net-web-api2,azure-web-sites
I'm running a webapi on an Azure website that makes calls to external web services. The webapi handles approximately 2K-3K requests per minute. Periodically, lots of socket errors start occurring that indicate: "An attempt was made to access a socket in a way forbidden by its access permissions". This error...
html,angularjs,angularjs-scope,asp.net-web-api2,scoping
Is a bad practice to be creating divs in your HTML just to be able to have multiple controllers? Since you cannot have them in one also the approach of having multiple directives with separate controllers seems like a hack, but correct me if I am wrong. So I have...
c#,asp.net-web-api,asp.net-web-api2
I want to create a REStful web service. This service returns "Meetings" for a certain day, week or months. I would create 3 Get methods which takes date values determined by the API user. GetMeetingsByDay(currentDate) GetMeetingsByWeek(startDate,endDate) GetMeetingsByMonth(startDate,endDate) Having 3 Get methods I could not access the API anymore just via...
asp.net,asp.net-web-api2
I've got the infamous Web Api No type was found that matches the controller name. I had this web service working until we did a little restructuring of the file system and classes and now I'm getting this error. The File system sits as default with the Controllers and Models...
c#,asp.net-web-api,asp.net-web-api2,owin,katana
The following EntryPointNotFoundException is being thrown in my OWIN Startup configuration upon executing UseWebApi(): An exception of type 'System.EntryPointNotFoundException' occurred in System.Web.Http.Owin.dll but was not handled in user code Additional information: Entry point was not found. Web API configuration: public class WebApiConfig { internal static void Register(HttpConfiguration config) { //...
entity-framework,asp.net-web-api2
It seems that Web Api 2 projects ship with Entity Framework 6 as standard. I am not currently lucky enough to be able to use EF6, so have been trying to get this working with an earlier version of EF. Is this going to cause issues?
c#,asp.net,asp.net-web-api2
Given the example on Using [FromUri]: public class GeoPoint { public double Latitude { get; set; } public double Longitude { get; set; } } public ValuesController : ApiController { public HttpResponseMessage Get([FromUri] GeoPoint location) { ... } } http://localhost/api/values/ and http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989 will both set Latitude and Longitude to 0...
routing,asp.net-web-api2,asp.net-web-api-routing
My WebApiConfig has following routes // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Employee", action = "Get", id = RouteParameter.Optional } ); The Post WebApi method has got following Signatures [HttpPost] public IHttpActionResult Post(Employee emp) { ..... } When i try to call...
serialization,entity-framework-6,asp.net-web-api2,aspnet-identity
The Visual Studio "Web API" project template includes endpoints for handling registration, authentication, and authorization of users. In a production application, however, users will typically be associated with other Entities as well, such as: public class Post { public Post() {}; public int Id { get; set; } public ApplicationUser...
c#,task-parallel-library,web-api,asp.net-web-api2
I've been seeing some conflicting information on the subject, and I would like to achieve some clarity here. Originally, you would have Web Api actions such as: Model Action(); HttpResponseMessage Action(); Then, with the addition of TPL enhancements to Web Api, you could have Task<Model> Action(); Task<HttpResponseMessage> Action(); And supposedly,...
asp.net-mvc,asp.net-mvc-4,asp.net-web-api,asp.net-mvc-5,asp.net-web-api2
I am working on .net web api in Asp.net Mvc5 project... By default it returns xml or json...in my project json/xml data returning fine... I am looking for the setting so that i can get response in JSONP.... Web Api config : public static void Register(HttpConfiguration config) { // Web...
asp.net-mvc,rest,asp.net-web-api2
I have created a Web API 2 project and although the APIs work fine, I must enter a trailing slash for them to do so. This results in a 404 http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699 This shows the JSON response as intended http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699/ I have another controller with a custom action that works fine....
asp.net-web-api,asp.net-web-api2
I want to understand why FromBody behave like this for common request. Case 1: Controller public void Post([FromBody]string value) { } POSTMAN Request Problem In this case value is my post method will not bind to value parameter to test. Case 2: Model public class Test { public string value...
c#,asp.net-web-api,unity,asp.net-web-api2,owin
I'm trying to use OWIN to Self-Host Web API while running my tests and I want to start it in BeforeEach and stop in AfterEach methods. All examples, that I found suggests to use using keyword, e.g. using (WebApp.Start<Startup>(url: baseAddress)) { ... } But in my case it doesn't help....
c#,rest,cors,asp.net-web-api2
I tried to follow the steps at http://enable-cors.org/server_aspnet.html to have my RESTful API (implemented with ASP.NET WebAPI2) work with cross origin requests (CORS Enabled). It's not working unless I modify the web.config. I installed WebApi Cors dependency: install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api Then in my App_Start I've got the class WebApiConfig...
c#,sql-server,entity-framework,ado.net,asp.net-web-api2
I have a DB in SQL Server with several tables. I have created a Class Library project in VS2013. Created a DBContext, added the database as a ADO.NET file and created a repository for running the queries. I have created a Web API2 empty project with a controller for creating...
entity-framework,mapping,one-to-many,code-first,asp.net-web-api2
I have 2 models, user & telephone. A user can have many telephone numbers. My User code: public class User { public User() { this.TelephoneNumbers = new List<Telephone>(); } public int UserId { get; set; } public string Forename { get; set; } public string Surname { get; set; }...
asp.net-web-api2,log4net-appender
Is it possible for log4net to log custom variables, or am I limited to the "pre-configured" variables? e.g. %appdomain: the friendly name of the appdomain from which the log entry was made %date: the local datetime when the log entry was made %exception: a formatted form of the exception object...
c#,asp.net,authentication,asp.net-web-api,asp.net-web-api2
I have a web api/angular app, which uses bearer tokens for authentication. The token just stops working after some time, and server starts to throw 401/unauthorized response. Since it all happens automatically, I'm not sure how to debug this. The token is being sent in headers, and works for first...
c#,asp.net,iis,asp.net-web-api2,iis-8.5
I'm making an Web API 2. Debugging on my local machine works fine. VS 2013 + IIS 8.0 The server is running Windows 2012 R2 + IIS 8.5 + Plesk v12 All my routes works fine when I debug it on my local machine.I'm using Postman and Fiddler to check...
entity-framework,linq-to-sql,asp.net-web-api,asp.net-mvc-5,asp.net-web-api2
I want to modify some fields after query, but the return value is changed after I modified the fields. I want to keep the IQueryable value after I modify it. How can I store the IQueryable value? public IQueryable<Book> GetBook(int id) { IQueryable<Book> Books = null; IQueryable<Book> Book_return = null;...
c#,asp.net,asp.net-web-api2
I have a web Api with a route to the Login Token setup in the Startup.Auth like so: PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), AllowInsecureHttp = false }; That should route my api...
asp.net-mvc,web-api,asp.net-web-api2,azure-active-directory,openid-connect
I'm trying to create a protected controller via Azure AD application roles. Here is an exempt from Startup.Auth, which is basically provided by Visual Studio template: public void ConfigureAuth(IAppBuilder app) { ApplicationDbContext db = new ApplicationDbContext(); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = Authority,...
asp.net-web-api,web-api,asp.net-web-api2
I found this example in google: public string GetValue([FromUri]Book b, [FromUri]Author a) { return b.Name + " ("+a.AuthorName+")"; } public string PostValue([FromBody]Person p) { return p.FirstName; } I can't understand what is the point of [FromUri] attribute if HTTP GET method send data only as part of the URl respectively,...
routes,asp.net-web-api2,attributerouting
I am trying attributed routing with Web API 2. I have defined a route prefix and I have two methods. The first one works but the second one fails [RoutePrefix("api/VolumeCap")] public class VolumeCapController : ApiController { [Route("{id:int}")] public IEnumerable<CustomType> Get(int id) { } [Route("{id:int}/{parameter1:alpha}")] public CustomType Get(int id, string parameter1)...
asp.net-web-api,routing,asp.net-web-api2,asp.net-web-api-routing,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...