FAQ Database Discussion Community


IIS hosted ASP.NET and SharePoint server libraries - authentication / security issue

asp.net,iis,sharepoint,asp.net-web-api,owin
I am currently working on a project where we are focused to develop as much as possible against the SharePoint CSOM library. Unfortunately CSOM offers no possibility to access Cross-Site-Publishing functionalities. So we decided to deploy a ASP.NET Web API web service on the target SharePoint system, which is hosted...

Odata web api 404 error

asp.net-web-api,odata
I am new to odata. I have builded a web api with a controller as shown below: using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Web.OData.Routing; namespace HelloWebApi.Controllers { public class TestsController : ODataController { // // GET: /Product/ ProductsContext db = new ProductsContext(); private bool TestExists(int key) { return db.tests.Any(p => p.key==...

Identity Framework create a new password for a user (without a password)

c#,asp.net-web-api,asp.net-identity
So, I have this site where users can only be created by administrators. I set up my Web API method like this: /// <summary> /// Creates a user (with password) /// </summary> /// <param name="model">The bound user model</param> /// <returns></returns> [HttpPost] [Route("")] public async Task<IHttpActionResult> CreateUser(UserBindingModel model) { // If...

ASP.Net WebAPI has different content type in different user agents

c#,asp.net,rest,asp.net-web-api,user-agent
I am trying to learn ASP.Net WebAPI, and I am having a hard time figuring out what is going on. I created a small application that contains an action like this: public IHttpActionResult Hello() { return Ok("Hi"); } This works fine, so I look at it in the browser. I...

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync

c#,asp.net-web-api,async-await,asp.net-identity
This is more of an async/await question than ASP.NET Identity. I am using Asp.Net Identity, and have a custom UserStore, with a customized GetRolesAsync method. The UserManager is called from a WebApi controller. public class MyWebApiController { private MyUserManager manager = new MyUserManager(new MyUserStore()); [HttpGet] public async Task<bool> MyWebApiMethod(int x)...

Asp.net Web API Routing by action name fix

asp.net-mvc,rest,asp.net-web-api,asp.net-routing
I found this article at asp.net Learn website. I use this article to help me to create an API method to search in the database by email and not id. However, if you take a look at the article, you will be able to help me fix my problem as...

WebAPI Converting JSON in to Strongly typed .net Object

c#,asp.net,json,asp.net-web-api
What I'm trying to do is send some JSON to a .net webserver the JSON looks like this. var mydata = { "filters": { "game": -1, "mediatype": -1, "location": -1, "contributor": -1 }, "tags": [1,2,3,4], "search": "", "startindex": 6, "fetchcount": 12 } From what I've been reading, Web API will...

Entity failed to be modified with Entity framework

c#,.net,asp.net-mvc,entity-framework,asp.net-web-api
I used Entity Framework in my Web Api application like this : [HttpPut] public System.Web.Mvc.JsonResult UpdateAccount(CollaborateurModel item) { if (ModelState.IsValid) { ApplicationUser user = UserManager.FindByIdAsync(item.id_user_fk).Result; user.Roles.Clear(); UserManager.AddToRoleAsync(item.id_user_fk, item.Role); ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item); repo.UpdateCollaborateur(entity); return new System.Web.Mvc.JsonResult { Data = true }; } else { return new System.Web.Mvc.JsonResult {...

How to have SimpleInjector resolve viewmodel dependencies?

asp.net-mvc,asp.net-web-api,dependency-injection,simple-injector
I'm trying to use SimpleInjector 2.7.3 (IoC container) within an Asp.Net MVC + Web API application. I've had a couple of problems trying to set it up for both MVC and Web API on the same project until I found this link: http://methoddev.com/blg/let-s-talk-software/310/simple-injector-in-asp-net-mvc-webapi After following the link's example, here's what...

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0

asp.net-web-api,datatables
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error. Hope someone sees the problem. The html markup: <input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar"...

Paging in .NET Web API

c#,.net,asp.net-web-api,odata,paging
I have to do paging for an odata endpoint built using Entity Framework . I know I can do it using private ODataQuerySettings settings = new ODataQuerySettings(); settings.PageSize = myPageSize; // I keep this value in web.config of solution and options.ApplyTo(IQueryable, settings); But I am constrained not to use ApplyTo...

Multiple entities with one web api controller

asp.net-mvc,asp.net-web-api
I am building a mvc based website with ef6 code first type db. Right now i have a web api controller named Categories Controller that works nicely and shells out json data to my js requests. // GET: api/Categories public IQueryable<Category> GetCategories() { return db.Categories; } Now I need to...

Allow console application to access Windows Authenticated web app

c#,asp.net,asp.net-mvc,iis,asp.net-web-api
I have a MVC web application which uses Windows Authentication. So we do things like System.Web.HttpContext.Current.User.Identity.Name Now there is a console app I'm writing that would be run as part of a batch job. All this console app needs to do is call an ActionResult in the main web app...

Web API and MVC in the same project with Session States

c#,asp.net-mvc,asp.net-web-api,session-state
I'm been working around an ASP .Net MVC application that is going take log in requests from different sites with different configurations (so I cannot use the FormsAuthentication SSO way). The way I decided to resolve this was by creating temporal login request tokens, so each token could be used...

Validate username and password without authenticating the user

asp.net-web-api,asp.net-identity-2
Using Asp.Net Identity 2.x with WebApi 2.x (both latest), is it possible to just validate a given username and password in order to know if the provided information is valid, without actually authenticating the user? I am working on a partial login in our identity service and it's essential that...

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

Javascript Date to C# Sortable (“s”) Format

javascript,c#,jquery,asp.net-web-api
I am trying to pass DateTime as string to my Web API service and parsing it to sortable datetime in c#. Please find the code below: public static DateTime? ToDateTime(this string dateTime) { if (string.IsNullOrEmpty(dateTime)) { return null; } return DateTime.ParseExact(dateTime, Constant.DateFormat, CultureInfo.InvariantCulture); } Client side code: var d =...

WEB API call stops working after introducing the “await” keyword

c#,asp.net-mvc,asp.net-web-api,.net-4.5,c#-5.0
I have a simple web api method which retrieves a list of items from a database. When the method looks like this it works and the items are displayed in the UI: [ActionName("GetServices")] public async Task<IHttpActionResult> GetServices() { var services = dbContext.Service.ToListAsync(); return Ok(services); } But as soon as I...

How can I change the Controller Naming Conventions in Asp.NET MVC?

c#,asp.net,asp.net-mvc,asp.net-web-api
I'm starting to develop in asp.NET MVC. I have a requirement to separate a Web API from View projects, I want WebAPI controllers to have different naming conventions from View project, to easily identify what is webapi controller from what is a controller for view. In both projects, the default...

Why web API return 404 when deploy to IIS

asp.net,asp.net-mvc,iis,asp.net-web-api
Windows Server 2012 R2, IIS, VS2013 I have implement a ASP.NET web api, when I debug in VS2013, it can open IE, and I can call my web api correctly. http://localhost:42508/api/log/111 I have use "publish" in VS2013, and deploy all files to D:\api_publish. Now, I set up IIS, and under...

Conditional OR with AuthorizationFilterAttributes in ASP.NET Web API 2

c#,asp.net,asp.net-web-api,asp.net-authorization
I am writing a controller action that can be accessed by one of two groups of users; each group has it's own implementation of AuthorizationFilterAttribute containing custom logic defining how the group be authorized. I want to be able to use a conditional OR to determine that at least one...

Is it nessesarry to send credentials on every single request to MVC Web Api?

authentication,asp.net-web-api,web-api
I am about to create my first restfull web service where i chose MVC WEB API to be the "provider". After reading about authentication i am a little confused. My requirements is that on call to any url of webservice i want client to be authenticated, except sign in url....

How to read header in controller constructor

asp.net-web-api
Is it possible to read header Authorization in my controller constructor? and how? and is this the best solution (reading header value in controller constructor) to achieve my goal ? the following is my code of my classes that inherit an interface: public interface IProvider { string SendData(string data); //other...

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

query multi-level entity with filter at the lowest level

c#,asp.net,asp.net-web-api,linq-to-entities
So I have 3 entity classes: public partial class Event { public Event() { Recurrences = new HashSet<Recurrence>(); } public int Id { get; set; } public ICollection<Recurrence> Recurrences { get; set; } } public partial class Recurrence { public Recurrence() { AspNetUsers = new HashSet<AspNetUser>(); } public int Id...

httpwebrequest GET retry when connection is lost

c#,asp.net-web-api
My application uses a httpwebrequest to GET certain information from my WebAPI. What I'm trying to do is retry the request if the connection is lost or if there is no connection at all. public static string httpsGET(string passedweburi, string BCO) { string content = ""; //GET method HttpWebRequest HttpRequest...

Posting JSON to an Azure Queue via an ApiController

c#,json,azure,asp.net-web-api,windows-azure-queues
I'm trying to receive a POST on an ApiController in ASP.NET Web API and add it to an Azure Queue. The problem I'm having is that I don't want todo parameter binding to a class's properties at this point but rather queue up the JSON as a string in the...

How to use the same route with different parameter types?

asp.net-web-api,asp.net-mvc-5,asp.net-mvc-routing,web-api,asp.net-web-api-routing
I have an Api controller with two different actions that take different parameter types. // GET: users/sample%40email.com [Route("users/{emailAddress}")] public IHttpActionResult GetUser(string emailAddress) // GET: users/1D8F6B90-9BD9-4CDD-BABB-372242AD9960 [Route("users/{reference}")] public IHttpActionResult GetUserByReference(Guid reference) Problem is multiple actions are found matching when I make a request to either. Looking at other answers I thought...

redirect to actionResult method from an api

c#,asp.net-mvc-4,asp.net-web-api
[HttpPost] public void insertData(string productid) { //insert to db string uri = this.Url.Link("Default", new { controller = "AddProducts", action = "Index" }); //Response.Redirect(Url.Action("", "")); } after inserting to the database i want to redirect to an actionResult method.i have a void method, what do i return it as?...

Use JSON data coming from WebApi in AngularJS application

json,angularjs,asp.net-web-api,web-api
I get some data from a WebApi, the answer (below the code to get the datas) is in JSON. But I can't access this result from angularJS. The datas look like : { "$id": "1", "result": [ { "$id": "2", "name": "Français", "code": "FR", "id": 1 }, { "$id": "3",...

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

How to secure a controller on WebAPI for use by only the local machine

c#,security,asp.net-web-api,certificate
I have an ASP.NET MVC website that makes use of WebAPI, SignalR. I wish for my server (the same server that hosts the website) to make HTTP requests to a WebAPI controller - I wish to do this so that I can hook into my website's SignalR functionality. I want...

How to validate email in ASP.NET Web API 2.0?

asp.net,asp.net-web-api,web-api
Please provide me regular expression to validate email id like below in web api method: // GET: users/sample%40email.com [Route("users/{emailAddress:regex()}")] public IHttpActionResult GetUser(string emailAddress) Here i need regular expression which will validate email like sample%40email.com and will work in :regex() of web api route attribute....

Web API AuthorizeAttribute does not return custom response

c#,asp.net-web-api,asp.net-mvc-5
How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

What's the best way to map objects into ember model from REST Web API?

json,rest,ember.js,asp.net-web-api,ember-data
The topic of this post is: my solution is too slow for a large query return. I have a Web Api serving REST results like below from a call to localhost:9090/api/invetories?id=1: [ { "inventory_id": "1", "film_id": "1", "store_id": "1", "last_update": "2/15/2006 5:09:17 AM" }, { "inventory_id": "2", "film_id": "1", "store_id":...

Web api access controller method from another controller method

c#,asp.net-web-api
I have two different controller --> Controller A,Controller B And I have different methods each controller and their return values IHttpActionResult (Method A controller A ,Method B and Controller B) How can I access another controller method and take its content from another controller Controller B ,and Inside Method B...

Passing complex array from Controller to View ASP.NET MVC

c#,asp.net,asp.net-mvc,asp.net-web-api
I have a model in my ASP.NET MVC application: public class SearchArrayModel { public long ID { get; set; } public string Name { get; set; } public struct AttribStruct { public string AttribName { get; set; } public string[] AttribValues { get; set; } } public AttribStruct[] AttribStructTable {...

How debug 401 unauthorized error?

c#,asp.net,.net,json,asp.net-web-api
I want to post json to the server, I created json and passing it. But getting The remote server returned an error: (401) Unauthorized error. Can some one help me with that. I have posted my code:---------------------------------------------------------- var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://synapsepay.com/api/v2/user/create"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter...

Passing JSON to WebApi in MVC5

c#,jquery,json,asp.net-web-api
im facing issues in syntax to pass json array from jquery to the webapi in my mvc5 project . Following is my code :- C# code:- //GET Instance // GET: api/PostDatas public IQueryable<PostData> GetPostDatas() { return db.PostDatas; } //POST Instance // POST: api/PostDatas [ResponseType(typeof(PostData))] public IHttpActionResult PostPostData(PostData postData) { if...

How to post content with & to a web api?

c#,asp.net-mvc,angularjs,asp.net-web-api
I have a problem to post a content with & like "M&A is the trend....",the message only stop at M MVC Web API [HttpPost] public IHttpActionResult Post([FromUri] CommentModel param) {} public class CommentModel { public int Id { get; set; } public string Message { get; set; } ... }...

how to post objects from angular to a webapi controller

javascript,c#,angularjs,asp.net-web-api,http-post
I am creating a pdf using pdfsharp. I need to pass the chart legend data(name,color) to the pdfsharp controller. I am using a angular $http post, a ajax post would be fine as well. the error I am getting is Request...

Null parameter on web api post method

c#,asp.net,asp.net-web-api
I have a very simple web api controller: public class CarrinhoController : ApiController { [HttpPost] public string Adiciona([FromBody] string conteudo) { return "<status>sucesso</status"; } } Now I'm running the server and trying to test this method via curl like this: curl --data "teste" http://localhost:52603/api/carrinho The request is arriving in my...

Exposing webapi to third party

asp.net-web-api,dto
How third party client would use my api methods who has no knowledge of my DTOs (the objects web service returns or takes as parameter). Do i need to expose my DTO's somehow?

Simple Injector Dependency Resolution Error

c#,.net,asp.net-web-api,dependency-injection,simple-injector
I am following onion architecture and using simple injector in the DependencyResolution Project. Here is my architecture: 1-Core - Domain Classes - Repository Interfaces - Service Interfaces 2-Infrastructure - Data - Dependency Resolution - Repository Interfaces Implementation - Service Interfaces Implementation 3-WebApi - Web Api Project 4-WebClient - My AngularJs...

How can we hide a property in WebAPI?

c#,asp.net-web-api
I have a model say under public class Device { public int DeviceId { get; set; } public string DeviceTokenIds { get; set; } public byte[] Data { get; set; } public string FilePwd { get; set; } } Now I have a ASP.net Web API where there is a...

Database error in web api

c#,sql,linq,asp.net-web-api,odata
I am trying to create an odata endpoint for a table valued function in sql database. I get the exception: The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. I am sure with my code and unable to...

Exposing localhost to the internet via tunneling (using ngrok): HTTP error 400: bad request; invalid hostname

asp.net,visual-studio-2012,asp.net-web-api,iis-express,ngrok
From previous versions of the question: (So there is this, which outlines pretty much what I've done so far...I've got the local IP working. Then I found ngrok, and apparently I don't need to connect via the IP.) What I am trying to do is expose my website running on...

Web api with mvc 6 get element based on string

c#,asp.net-mvc,asp.net-web-api,asp.net-5,asp.net-mvc-6
I am creating a web api using mvc 6. now i am trying to get a element from my db. the key in this table is a string (email adress). i do not have acces to this database so i cant change the key of this table. Now when creating...

Ajax calls to a web api method

c#,jquery,ajax,asp.net-mvc,asp.net-web-api
I have this view : <div id="addDisplay" class="display"> <div class="box-header"> <h3 class="box-title">Ajouter un compte</h3> </div> @{ AjaxOptions addAjaxOpts = new AjaxOptions { // options will go here OnSuccess = "getData", OnFailure="selectView('add')", HttpMethod = "Post", Url = "/api/AccountManage/CreateAccount" }; } @using (Ajax.BeginForm(addAjaxOpts)) { @Html.Hidden("id", 0) <p> <label>Statut social </label> <select id="marital_status"...

Manually validate Model in Web api controller

asp.net,asp.net-mvc,asp.net-web-api
I have a class called 'User' and a property 'Name' public class User { [Required] public string Name { get; set; } } And api controller method is public IHttpActionResult PostUser() { User u = new User(); u.Name = null; if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(u); } How do i...

How to set the OnClientClick value - syntax?

javascript,asp.net,vb.net,asp.net-web-api,onclientclick
ASP.NET coding in VB.NET -- web application. I am asking a few questions about the "proper way" to set the OnClientClick phrase in the aspx button declaration. Option 1: leading with 'javascript:' and surrounding the js in {...} <asp:Button ID="btnDelete" runat="server" CausesValidation="False" SkinID="cmdButton" style="margin-left: 2em;" CommandName="Delete" Text="Delete" OnClientClick = "javascript:{(!confirm('Do...

Web API translating input into random int

c#,post,asp.net-web-api,json.net
not sure whether the subject is the best description for this problem but I am getting an unusual problem where I have a single Web API operation and a single field on a request and for some odd reason the value gets manipulated. Depending on the input this gets converted...

Sending file contents from php curl (using post) to c# webapi

c#,php,asp.net,curl,asp.net-web-api
I have to transfer a file object from php to c# webapi. Somehow, in c#, the file contents are coming as Null. This is the partial PHP code after taking out the other stuff <?php $fileContents = file_get_contents($_FILES['fileToUpload']['tmp_name']); $uploadFile = new UploadFile(); //custom object $uploadFile->fileName = "test"; //string $uploadFile->fileContent =...

Cannot read property 'client' of undefined using SignalR

asp.net-web-api,signalr,signalr-hub
I've been working all day on this with no luck. I have also tried (almost) every single SO question, but I didn't get it to work... I'm running web api with very simple SignalR push message and separately simple front end to show this push message. In my case the...

ASP.NET 5 Web API doesn't return XML

xml,asp.net-web-api,content-type,asp.net-5
How can I have my vnext API to return XML and JSON ? I thought that using content-type with application/xml would work as it was before. Note that I tryed with Accept : application/xml too. But it seems not. EDIT : this is my project.json file : { "webroot": "wwwroot",...

Access the web project's folder from the WebAPI project

c#,asp.net-mvc,asp.net-web-api
My Asp.Net MVC project's folder structure is as shown above.Could you tell me how to access the web project's event-images folder from the webapi project ? I have implemented where I can access the webapi's event-images folder as shown below. Now I need to access web project's event-imagesfolder.How can...

Is there an Ajax call generator from webapi

javascript,ajax,asp.net-web-api
I'm writing a web api c# code, i.e: public void Post([FromBody]List<ImageModel> images,string id) { where ImageModel is: public class ImageModel { public string fileName { get; set; } public bool isApproved { get; set; } public [another object...] cropped { get; set; } } I'm looking for a tool that...

Web API Parameter Path Too Long

javascript,c#,angularjs,asp.net-web-api
I'm making this call to a Web API method: var url = rootWebApiUrl + '/api/services/files/' + $scope.selectedServer.Name + "/" + encodeURIComponent(fullPath) + '/'; $http.get(url) // rest of $http.get here... Because the fullPath variable is long, I get a path too long error on the PhysicalPath property in a framework method...

OAuthorization through app or web api

android,asp.net-web-api,oauth
My question is pretty straightforward but I am pretty sure it's just a lack of understanding on my part. Background: I have a prototype native android app as well as an asp.net Web API and I want to implement OAuthorization so that users can login through google+, Facebook, or Twitter....

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

Json method is not recognized in Web Api controller

c#,.net,json,asp.net-mvc,asp.net-web-api
I have an web api controller using sport.BLL.Abstract; using sport.BLL.Concrete; using sport.DAL.Entities; using sport.webApi.Models; using AutoMapper; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using System.Web.WebPages.Html; namespace sport.webApi.Controllers { public class...

Web API - Controller Design

javascript,c#,asp.net-web-api
I have a Web API project that currently has a ServicesController. I get the list of services, for a server, by making this call: $http.get(rootWebApiUrl + '/api/services/' + server) The ServicesController has this signature: public IEnumerable<FirstSolarService> Get(string id) Now I want to make two more calls. Get the Windows folders...

How can I handle exceptions in Web API 1.0 at my BaseAPIController

.net,asp.net-web-api
I am currently using Web API 1.0 and .NET 4.0 I need a function that can take care of the noise of catching and handling exceptions in my Base API so that I dont need to write that in every RESTful operation. public int Get(WelcomeTeamNotes note) { try { return...

Can't access any of Linq methods

linq,asp.net-web-api
I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

struct table inside struct - ASP.NET - allegro webAPI

c#,asp.net,asp.net-web-api,struct
I stopped in one point. I'm writing a small ASP.NET application with WebAPI from polish site allegro.pl (it's similiar to ebay.com) This API have a method which returns me some data: (...) 3. searchArray | SearchResponseType[] Struct table, where are the information about offers that matches the question (...) Inside...

No 'Access-Control-Allow-Origin' header on one site, but not on another

c#,jquery,ajax,asp.net-web-api,cors
We have a system made up of a website, written in ASP.NET/MVC, and a webservices site, written in ASP.NET/WEBAPI. The user loads pages from the website, which make AJAX calls into the webservices site, using JQuery. We're building this with VS2013, and deploying it with MS's Web Deploy, run from...

WebAPI 2.0 Post and Delete Routes

c#,asp.net-web-api,asp.net-web-api-routing
I have two actions on the same controller, with identical routes, but separate HttpMethod requirements (POST vs DELETE). [AllowAnonymous] public class TestController : ApiController { [Route("~/api/test")] [HttpDelete] public IHttpActionResult Endpoint1() { return this.Ok("endpoint1"); } [Route("~/api/test")] [HttpPost] public IHttpActionResult Endpoint2() { return this.Ok("endpoint2"); } } This is all fine -- both...

.NET web API calls are getting intercepted by angular js UI Router, returning HTML instead of calling API

javascript,angularjs,asp.net-web-api
I have an angularjs app, that sits on top of an MVC5 app and an WEB API backend. I am using UI Router for the Angular js routing and for now, have removed ALL $urlRouterProvider.when and $urlRouterProvider.otherwise calls, but still when I try to do a $http:get... it is returning...

WebApi Put how to tell not specified properties from specified properties set to null?

c#,.net,json,asp.net-web-api
Here is the scenario. There is an web api put call to change an object in sql server database. We want only to change the fields on the database object if they were explicitly specified on webapi call json. For example: { "Name":"newName", "Colour":null } That should change the Name...

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

Authenticate WEB API request with action params

asp.net,asp.net-mvc,asp.net-web-api
I am interested how to do a MVC WEB API autorization. I have checked basic authentication , but I have a different scenario. In my case login params are expected as an action parameter and not inside header. namespace Test.Controllers { public class TestController : Controller { [RequireHttps] [Authorize] public...

File.Move is not working as expected

c#,asp.net-mvc,asp.net-web-api
File.Move(@"/Resources/images/temp/" + xx, @"/Resources/images/event-images/" + newFile); // Try to move The File.Move is also not working.How can I use it with relative paths ? Could you tell me how to sort out above issue.Thanks in advance....

Validate access token for WEB API protected by Azure AD

azure,asp.net-web-api,azure-active-directory
I'm playing with Azure AD authentication and authorization scenarios and not all clear for me. Currently I'm looking at SinglePageApp-WebAPI-AngularJS-DotNet sample project. And one thing that I can't understand. On the client side we get access token using implicit grant flow - that is clear. Then we send request to...

Is there a way to use AutoFac Web Api Authorization Filters through Attributes instead of injection?

asp.net-web-api,filter,dependency-injection,authorization,autofac
I have an Autofac Web Api Authorization Filter like that: public class MyAuthorizationFilter : IAutofacAuthorizationFilter { public void OnAuthorization(HttpActionContext actionContext){} } public class MyAuthorizationAttribute : Attribute { public MyAuthorizationAttribute() { } } Right now the only way I can have an Autofac Web Api Authorization Filter is through injecting it...

OnAuthorization Method of AuthorizationFilterAttribute will execute every time when request arrives?

c#,asp.net-web-api
I am writing Web API ( v2.2 ) for accessing another REST API. Reason is that I want restrict some functional and provide more friendly data. In short I am writing wrapper for some REST API. I am providing authentication/authorization via my Implementation of AuthorizationFilterAttribute. Here is snippet of code:...

Creating helppage for a webapi c#

c#,asp.net-web-api
I want to create a help page for webapi in C#. I am using GetApiExplorer and ParameterDescriptor.ParameterType.GetProperties(). Everything is good but when the input is a list of complex type. Then the output that I get is of list not the complex type. How to get the complex type of...

Web API Controller not found on PUT

jquery,asp.net-mvc,asp.net-web-api,asp.net-mvc-5,put
I am having trouble finding the put action of a web api 2 controller. I'm using MVC5. The GET action in the controller is found and is working well when called. I have tried several different ways of hitting this, but to no avail. I would appreciate any hints. The...

Onion Architecture Identity Framework

asp.net,.net,asp.net-web-api,asp.net-identity,onion-architecture
I am following Onion Architecture. And in that I am using ASP.NET Identity Framework. Here is my Project Structure: 1-Core - Domain Classes //It contains my T4 template classes -- AppUser //It is Identity User. - Repository Interfaces - Service Interfaces 2-Infrastructure - Data //It contains my edmx file, I...

What's the equivalent of CastleWindsor's container.Release in LightInject?

asp.net-web-api,dependency-injection,castle-windsor,light-inject
I saw ASP.NET Web API dependency injection in Seemann's site. It uses CastleWindsor though. request.RegisterForDispose( new Release( () => this.container.Release(controller))); What's the equivalent of CastleWindsor's container.Release in LightInject? http://blog.ploeh.dk/2012/10/03/DependencyInjectioninASP.NETWebAPIwithCastleWindsor/...

Web API Basic Auth inside an MVC app with Identity Auth

c#,authentication,asp.net-web-api,asp.net-mvc-5
So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep...

Method not found in Web API 2

c#,rest,asp.net-web-api
Im trying to figure out how to use Web API. I have gone through some tutorials and now Im trying to set up my web service. I have a really hard time trying to figure out why it cant find my methods. To me it just seems like random (the...

AngularJS binding not occurring on page until a user action

angularjs,asp.net-web-api,angularjs-ng-repeat,azure-mobile-services
I've got my first angular app which displays some data from a list via ng-repeat. The controller for the view sets a few variables to scope - some directly in the function and another from an API call. The data from the in function load is showing up in that...

Web Api 2 or Generic Handler to serve images?

c#,asp.net,asp.net-web-api
I want to create an image handler, but i am torn between using Web API 2 or just a normal Generic Handler (ashx) I have implemented both in the past, but which one is the most correct one. I found an old SO post LINK but is it still really...

FROM Http Header not included unless it's a valid email address

asp.net,google-chrome,http,asp.net-web-api,http-headers
I'm using the Advanced Rest Client Chrome extension to test a request to a Web API 2 endpoint. I'm trying to include a value in the "From" header but the value is null when it is not a valid email address. By reading the spec, it looks like it only...

Using Swashbuckle to Host an Existing Swagger.JSON file

asp.net-mvc,asp.net-web-api,swagger,swashbuckle
I have an existing Swagger.json file for a .NET WebApi site which I would like to integrate with my developer site (which is at a different url) running Swashbuckle. Can I simply copy this swagger.json file to the mvc site (content or app_data folder and do this?) If I can,...

Bearer token in MVC controller to access Web API

asp.net-web-api,oauth,oauth-2.0,bearer-token
I have two projects: MVC, Web Api In the Web API project I am using bearer token authentication. This token expires after 24 hours. In my MVC project I'd like to call the Web api project via MVC controller (server to server). What's the best way to: Get a token...

encodeURIComponent Not Working with Web API Call

javascript,c#,asp.net-web-api
I'm getting a 404 Not Found when making this call: var url = rootWebApiUrl + '/folders/' + $scope.selectedServer.Name + "/" + serviceName; $http.get(url) // the rest of this line doesn't matter for this issue I thought that maybe using encodeURIComponent would help, but I get the same 404 Not Found...

Where should I store WebAPI controllers inside ASP.NET-MVC 5 project?

asp.net-mvc,asp.net-web-api,odata
I have completed an ASP.NET-MVC5 application(website) where I have lot of MVC controllers: I would like to extent the functionality of my application by exposing WEB API with OData. For instance I would like to create another controller for Person model class, but this time it should be Web API...

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.

Retrieve information from Bearer Token

asp.net-web-api,claims-based-identity,claims,bearer-token
I have an MVC website that is calling a WebAPI in another project. The WebAPI uses OWIN and implements OAuth security. I will be using a Bearer Token to communicate between the MVC and WebAPI applications. My website requires the user to be in AD, which I am checking in...

Exclude underlying objects when storing data using EF6

asp.net,entity-framework,asp.net-web-api
I have a class Ticket which has some properties. Three of these (View, Task and Key) properties are navigation properties. Those properties already exist in database even before a ticket has been stored. In my application I load those properties from the database first and then create a Ticket object....

How to test a WebApi service?

c#,asp.net,rest,visual-studio-2012,asp.net-web-api
I'm really new to WebApi and I've been reading information about it but I don't know how to start my application. I already had a project with many WFC services with .Net 3.5. So, I updated my project to 4.5.1. Then I created a controller with the Visual Studio 2012...

Multiple C# WebAPI API routes - restrict API method to one of the routes

c#,asp.net-web-api,asp.net-apicontroller,mvcroutehandler
I have multiple routes for my API like config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{token}/{controller}/{action}", defaults: null, constraints: null, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new ApiTokenValidator() }) ); config.Routes.MapHttpRoute( name: "LoginApi", routeTemplate: "api/{controller}/{action}", defaults: null, constraints: null, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] {...

How to setup Request.Header in FakeHttpContext for Unit Testing

c#,unit-testing,asp.net-web-api,httpcontext
I have a FakeHttpContext I have been trying to modify to include some headers for testing purposes public static HttpContext FakeHttpContext() { var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id",...

Enforce ordering of OData items even when $top is used

linq,entity-framework,asp.net-web-api,odata,iqueryable
I have a DbSet<Items> collection. The primary key is a Guid. I don't want to order by this primary key. I want to order by an editable decimal property named "Order". The code I have is very simple, and it works great until the user puts a "$top" parameter into...

solution architecture for an OData / Web API based .Net project

c#,asp.net,asp.net-web-api,odata
so far in my office i have developed a number of small and medium sized .Net web based applications where i used to architect them something like this - Web layer (.Net Web APIs) Controllers, filters Services (contains business logic) IServices Repository (gets data from database using entity framework /...

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

consuming REST service, method returning multiple types .. what to do

asp.net-mvc,rest,asp.net-web-api
I am consuming someone elses REST service for my app. the problem is that each request can return 1 of 3 different types when responding either: the expected successfull response type an error response which wraps the 500 (Error) a validation error response (ValidationErrors) I am currently calling the service...

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