FAQ Database Discussion Community


XSS in angularjs app and web api 2

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....

Getting 404 error while calling Web API 2 from MVC 5 application

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:...

How to use single object and fill its properties throughout all sub process in single webapi request?

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...

OData Annotations do not appear when not localhost

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...

web api FromUri and FromBody attributes misunderstanding

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,...

How to properly implement asynchronicity in web api 2

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,...

Should I return a status code or throw an exception in .Net Web Api 2

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) {...

Passing Authentication from WebApp to WebAPI using BreezeJS

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...

OWIN Startup: Entry point was not found

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) { //...

Serve large file async and then delete it

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...

Windows Phone HttpClient GetAsync performance

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...

Create a RESTful service with 3 similar Get methods

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...

Unable to inject with unity a complex type to web api 2

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...

Azure AD application roles

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,...

How to decide what entities to store in a database

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...

web api route with optional parameter

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 =...

Enabling CORS through Web.config vs WebApiConfig and Controller attributes

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....

How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?

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...

Web API Returning a 405. Shouldn't it be a 404?

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...

Get Content-Disposition parameters

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 =...

Using '.' in Web Api using Attribute Routing is giving 404 error

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...

One to Many entity framework error

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; }...

Automapper returns null object, source object is not null. Why is that so?

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;...

Manually dispose OWIN WebApp

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....

how to update multiple data in entityframework through async web api

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...

How to get .net web api in jsonP, although it returns json data by default

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...

File upload web api 2.0 error after deployment on IIS 8.5

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...

my Web API C#.net server is not able to Deserialize JSON Object

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...

JSON.NET Parsing Full Key-Value Pair as Key

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...

Deserializing inherited classes

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...

Why is there time difference between client and server on localhost

.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...

Performance Issues with Include in Entity Framework

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...

Web Api2 and protected setters?

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;...

How to send a custom object from OnException method?

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...

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

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...

How, I can use select with max,min function in (linq and lambda)?

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!...

Why FromBody Behave like this ?

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...

Autofac - DelegatingHandler (HttpMessageHandler) Registration

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 ) {}...

Web API 2 POST-request return null

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:...

How to filter an odata $expand query in a Web-Api controller

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 {...

cast actionContext.ActionArguments to generic type - problems casting to generic type

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...

Log4Net Logging Variables

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...

How do I serialize an IdentityUser reference in Web API 2.2?

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...

Web API 2 Error 401.0 with IIS8.5 on one MapHttpRoute

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...

Web API 2 identity. /Token Always return 404 error

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:...

The route template separator character '/' cannot appear consecutively - Attribute routing issue

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);...

Api calls are blocked by $urlRouterProvider.otherwise('/') if the API is in the same project

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....

gson JsonSyntaxException to Java Date from .net DateTime

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:...

Auth token gets invalidates for unknown reason

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...

Leverage MultipleApiVersions in Swagger with attribute versioning

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...

Why can't I allow '*' characters in webapi routes safely? (or, if it can, how?)

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...

Web Api and where should I contorol Request Header data

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.

Unit testing ASP.NET Web API 2 Controller which returns custom result

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;...

REST API response standards: Timezone

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":...

Json parameter casting inheritance web api 2

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...

Which Versions of Entity Framework are Compatible with Web API 2?

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?

How to correctly use Data Annotations to select which Items should be returned by the Web API?

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...

Is it bad practice to create Divs just to have multiple controllers?

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...

How to make it explicit in Web API 2 for Entity Framework to only add parts of the object that have changed?

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...

Unable to return type Microsoft.Azure.Documents.Document from web api

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...

Web Api 2 Controller behaves different in Visual Studio 2012 vs 2013, Authorize Attribute

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...

How to specify url for $resource for oData v4

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...

Using A Service DB Context as WebApi OData Context

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...

Compiler warning when using AuthorizationFilters with async method calls

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...

WebApi Routing issue - unable to route to required action

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)...

No type was found that matches the controller name

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...

How do you enforce required query string parameters in Web API 2?

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...

Web API 2.2 OData Controller supporting class hierarchy

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...

Web API 2 requires trailing slash for custom attribute routing to work

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....

how to handle multiple developer environment in web.config

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...

MediaFormatter or ModelBinder for web api PUT method

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...

Can I receive a JavaScript Object on an API WITHOUT a Corresponding C# Object?

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...

Azure website global memory sharing/cache synchronicity

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...

How to configure OData end point in a self-hosted Web API application

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();...

How to create controller method that is only available for users that are not authenticated?

.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...

Simple.OData.Client - Unable to invoke Action that accepts entity collection parameter

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...

Allow class properties to be null in WebAPI 2 post methods

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;...

How to loop through all register api routes?

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 }...

Nothing happens when Angular Href is clicked

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...

WriteJson override with JSON.NET library

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...

Entity Framework throws Invalid object name

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...

Web API 2 modify db in GET method

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;...

Handle bad access_token sent through request using Web API 2 C#

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...

Null binding from POST request body

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...

WebApi Serving Videos on Mobile Devices

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....

web api Bad Request when getting access token after moving to production

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()...

Web Api 2 with two method with the same HTTP verb an angularjs resources

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...

PostAsync to /Token returns Internal server error

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...

Ninject won't resolve constructor dependencies - Web API 2

.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...

OData not working behind router with port address translation (port forwarding)

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...

Method not found: 'System.String System.String.Format(System.IFormatProvider, System.String, System.Object)

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...

Passing POST parameter to WEB API2

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...

Attributed Routing with multiple parameters in Web API 2

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)...

Web Api Parameter binding Inconsistent

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...

WebApi Routing not working for Post

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...

Hiding Get-Action in Web API (mvc)

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...

Route parameter with slash ā€œ/ā€ in URL

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:...

How to get HttpRequestBase from IOwinContext

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)...

How to register per request dependencies using StructureMap, MVC 5, and WebApi 2?

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...

Azure website An attempt was made to access a socket in a way forbidden by its access permissions

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...