Quantcast
Channel: Web API
Viewing all 4850 articles
Browse latest View live

Validating Boolean Values

$
0
0

Using WebApi 2, I have a model that contains a Boolean value:

[Display(Name = "notify")]
[DataMember]
public bool notify
        { get; set; }

The input format is JSON.  ModelState will reject any value other than lower case "true" / "false."   Therefore, if a user sends in "FALSE" or "False" or "1" then there is a fail.  Is there a noted way to accept these values without 1) changing the "notify" field to string and 2) without having to write custom code?

Thanks,

cj


How to return my custom class from my web api action

$
0
0

suppose this is my class which i like to return from my action

    public class Response
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public object ResponseData { get; set; }

        public Response(bool status, string message, object data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }

OR

    public class Response<T>
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public IEnumerable<T> ResponseData { get; set; }

        public Response(bool status, string message, IEnumerable<T> data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }

now this way i am wrapping output into response class and return from web api action

[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
    var Response=new Response(true, "SUCCESS", repository.GetAll());
    return Response;
    return Request.CreateResponse(HttpStatusCode.OK, Response);
    HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
    return response;
}

but json is not coming to client. where i made the mistake in code ?

i need to get json when i will invoke the above action from fiddler. please guide me how to fix the above code a result right json of Response class should return to client?

please give fresh and rectified working code copy of above one. thanks

ASP.NET Web API 2 compatibility

$
0
0

WEB API II,  is posible install in a Windows Server 2012 64BITs, with framework 4.5, ISS v.8?

Can't pass data from json to web api

$
0
0

This is just killing me.

It SHOULD be so easy.

I've written a Web API that I need to call from json, passing arguments and getting a return value (to the json). I'm using POST because I need to pass a really long string.

I know that my json code is calling the appropriate function because I've seen it happen in the debugger. But the parameter that is passed in is null even though I know for a fact that the json is passing a value. My code for post is returning a value that the json recognizes so the connection is right. It's just the values.

// POST api/values public string Post([FromBody] string counter) {     string retVal;     retVal = "Sent [" + counter + "]"; //counter (parameter) is always null     return retVal; //works just fine }

Here is the json code.

       var counter = { counter: $('#counter').val() };

        // I've also tried $.post(uri, 'Hello World')

        $.post(uri, counter)        

         .done(function (data) {             alert('success: ' + data);         })         .fail(function () {             alert('error: ' + Error);         });

Can anyone tell me what I'm doing wrong?

TIA

Rik Brooks

How to pass Auth Header in web api

$
0
0

Hi,

I have to use one below third party weebAPI, but I am unable to use 3rd API,

can anyone help me to resolve my query.

<div class="col-md-3">
  • UserEntity
  • EmailAddress
  • Password
</div> <div class="col-md-3">
  • SessionEntity
  • SessionCypher
  • ValidThrough
</div> <div class="col-md-3">
  • DirectoryEntryEntity
  • Id
  • TypeId
  • TypeDescription (either 'Folder' or 'File')
  • Name
</div>
URIVerbInput EntityRequiredReturn EntityResponse Codes 
https://my.rpsins.com/resume/api/UserPOSTUserEntityEmailAddress, PasswordUserEntity201 403Creates User for Authentication
https://my.rpsins.com/resume/api/SessionPOSTUserEntityEmailAddress, PasswordSessionEntity201 403Returns Session Token for Authentication Header Test Session
https://my.rpsins.com/resume/api/DirectoryEntriesGET Auth Header:TestSessionArray of DirectoryEntryEntity201 403Returns list of root directory directory entries

Web API, problems with XML and POST

$
0
0

I think that I have found a bug with webapi. Seen a couple of people having problems with this and there seems to be a pattern.

A simple service to initiate a print of invoices. Taking three parameters which are sent in as XML in a post request.

public HttpResponseMessage Post([FromBody]PrintRequest value)
{
var response = Request.CreateResponse<PrintRequest>(HttpStatusCode.Accepted, value);
return response;
}
public class PrintRequest
{
public string A { get; set; } 
public string B { get; set; }
public string C { get; set; } 
}

When posting the XML to the REST service the order of the parameters decides if they will be parsed or not. The alphabetical order of the parameters that is.

<PrintRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/InvoiceService.Models"><a>A</a><b>B</b> <c>C</c> </PrintRequest>

With the order as described above all parameters are initiated.

If the order is B, A, C only B and C will be initiated. Same result with the order B, C, A
If the order is C, A, B or C, B, A only C will be initiated.

From the tests I have performed my conclusion is that there is a bug in MVC4 Web API which puts a hard requirement on incoming parameters. Making all parameters that are out of order, later in the xml, fail to be parsed and initiated.

Is there any solutions to this? A patch coming soon perhaps?

Since this force the calling client to know of these limitations in the web api it kind of breaks web api for use with external parties. And we would prefer to have the option to use it where REST services are to prefer over SOAP ones.

Trying to prove out JWT with Web Api and x509 Certificates

$
0
0

Hi,

I am trying to use the Web Api and System.IdentityModel.Token.Jwt to do the following:

  • Create a JWT signed with an x509 Certificate.
  • Consume and validate the JWT signature.

I am new to the Web Api world so my terminology may be slightly off.  I'm getting errors on the validation of the token.

Here is the error I'm encountering trying to provide the SigningCredentials

{"IDX10618: AsymmetricSecurityKey.GetHashAlgorithmForSignature( 'HS256' ) threw an exception.\n AsymmetricSecurityKey: 'System.IdentityModel.Tokens.X509AsymmetricSecurityKey'\n SignatureAlgorithm: 'HS256', check to make sure the SignatureAlgorithm is supported.\nException: 'System.NotSupportedException: Crypto algorithm 'HS256' not supported in this context.\r\n   at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetHashAlgorithmForSignature(String algorithm)\r\n   at System.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(AsymmetricSecurityKey key, String algorithm, Boolean willCreateSignatures)'."}

Here is the code to "try" to generate the JWT.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace WebApiClient1
{
    class resttest2
    {

        private String GetJWTToken()
        {
            
            //Claim
            var claimsIdentity = new ClaimsIdentity(new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, "myemail@myprovider.com"),
                new Claim(ClaimTypes.Role, "Administrator"),
            }, "Custom");


            //create the token
            System.IdentityModel.Tokens.SecurityToken token;
            System.IdentityModel.Tokens.JwtSecurityTokenHandler handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.SecurityTokenDescriptor descriptor = new System.IdentityModel.Tokens.SecurityTokenDescriptor();
            descriptor.TokenIssuerName = "MikeTokenIss";
            descriptor.Subject = claimsIdentity;
            descriptor.SigningCredentials = GetSigningCredentials();
            descriptor.Lifetime = new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.Now, null);

            token = handler.CreateToken(descriptor);
            var tokenstr = handler.WriteToken(token);
            return tokenstr;
        }

        private SigningCredentials GetSigningCredentials()
        {
            X509Certificate2 cert = new X509Certificate2("C:\\mike.pfx", "passwordforpfx");
            SigningCredentials creds = new X509SigningCredentials(cert, JwtAlgorithms.HMAC_SHA256, cert.GetKeyAlgorithm());
            return creds;
        }
        private AuthenticationHeaderValue GetAuthHeader()
        {
            AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Bearer", GetJWTToken());
            return authHeader;
        }

        public class LoggingHandler : DelegatingHandler
        {
            public LoggingHandler(HttpMessageHandler innerHandler)
                : base(innerHandler)
            {
            }

            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                Console.WriteLine("Request:");
                Console.WriteLine(request.ToString());
                if (request.Content != null)
                {
                    Console.WriteLine(await request.Content.ReadAsStringAsync());
                }
                Console.WriteLine();

                HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

                Console.WriteLine("Response:");
                Console.WriteLine(response.ToString());
                if (response.Content != null)
                {
                    Console.WriteLine(await response.Content.ReadAsStringAsync());
                }
                Console.WriteLine();

                return response;
            }
        }

        public async Task LocalRunAsync()
        {
            //using (var client = new System.Net.Http.HttpClient())
            using (
                var client = new HttpClient(new LoggingHandler(new HttpClientHandler()))
                )
            {
                Console.WriteLine("In RunAsync");
                client.BaseAddress = new Uri("http://localhost/RestTestMike20160825/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = GetAuthHeader();
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetToken().ToString());
                Console.WriteLine("Added Headers");
                // HTTP GET

                System.Net.Http.HttpResponseMessage response = await client.GetAsync("api/products");
                Console.WriteLine("Called api/products/1");

                if (response.IsSuccessStatusCode)
                {
                    List<Product> output = default(List<Product>);


                    var jsonAsString = await response.Content.ReadAsStringAsync();
                    output = JsonConvert.DeserializeObject<List<Product>>(jsonAsString);
                    foreach (Product p in output)
                    {
                        Console.WriteLine("{0}\t${1}\t{2}", p.name, p.price, p.category);
                    }

                }
                else
                {
                    Console.WriteLine("Failure: " + response.ReasonPhrase);
                }

            }
        }


    }
}

Thanks in advance.

Web API2 WebHostBufferPolicySelector UseBufferedInputStream override

$
0
0

Hello,

I would like to ask if it is necessary to override  UseBufferedInputStream  method in Custom WebHostBufferPolicySelector, where base on rout i can turon on/off buffering.

What i mean is that I am uploading large file through API and I want to use streaming, so I wont use that much of memory, I heard that by default WEB API is buffering request and i want to avoid it, so according to some materials What i have done is:

 public class NoBufferWebHostPolicySelector : WebHostBufferPolicySelector
    {
        public override bool UseBufferedInputStream(object hostContext)
        {
            var context = hostContext as HttpContextBase;

            if (context != null)
            {
                if (string.Equals(context.Request.RequestContext.RouteData.Values["controller"].ToString(), "upload", StringComparison.InvariantCultureIgnoreCase))
                    return false;
            }

            return true;
        }
        //redundad
        public override bool UseBufferedOutputStream(HttpResponseMessage response)
        {
            return base.UseBufferedOutputStream(response);
        }
    }

-----
 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferWebHostPolicySelector());

        }

But then UseBufferedInputStream  method is called, context.Request.RequestContext.RouteData is always empty.

So now i am wondering if this is really thing I need to do, and if so, why I have context.Request.RequestContext.RouteData empty in this method.

Anyone can help me?


How to send xml to web api action

$
0
0

please give me a sample of web api action where i like to send person data in xml format.

give me two sample code one is web api action which accept person data and one is httpclient which will send person data in xml format ?

do i need to set anything to accept header for sending xml data ?

please help me with sample code.

We migrated from Self-hosted to OWIN, then FATAL error System.IndexOutOfRangeException

$
0
0

Hi,

We had Self-hosted Web API with log4net logging handler. Then we migrated to OWIN and add one LoggingMiddleware wiht log4net and deploy to PROD

One hour API was working ok, but after we got FATAL error

[Logentries Log Appender] FATAL Topshelf.Runtime.Windows.WindowsServiceHost The service threw an unhandled exception System.IndexOutOfRangeException: Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.

at System.Buffer.InternalBlockCopy(Array src, Int32 srcOffsetBytes, Array dst, Int32 dstOffsetBytes, Int32 byteCount)
at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.IO.TextWriter.SyncTextWriter.Write(Char[] buffer, Int32 index, Int32 count)
at Microsoft.Owin.Hosting.Tracing.DualWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.IO.TextWriter.WriteLine(String value)
at System.Diagnostics.TextWriterTraceListener.WriteLine(String message)
at System.Diagnostics.TraceInternal.WriteLine(String message)
at LogentriesCore.Net.AsyncLogger.WriteDebugMessages(String message)
at LogentriesCore.Net.AsyncLogger.Run()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

INFO XXXXXService ClientAPI TcpConnection closed:

Received bytes: 539304, Sent bytes: 127013
Send calls: 491, callbacks: 491
Receive calls: 549, callbacks: 549
Close reason: [Success] Socket closed

And then our API didn't response and every time we have error in log:

ERROR XXXX.WebApi.Host Exception thrown by subscription callback

Exception:

System.AggregateException: One or more errors occurred. ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "YYYYYYYYYYYYY", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, ZZZZZZZZZZZZZZZZZ, is an interface and cannot be constructed. Are you missing a type mapping?

---> System.InvalidOperationException: The current type, XXXXXXXXXXXX, is an interface and cannot be constructed. Are you missing a type mapping?

at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
--- End of inner exception stack trace ---
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)

Can't connect to GoogleMapsAPI when 'target machine actively refused it'?

$
0
0

I'm using the GoogleMapsAPI to return some location data which I am using in a ASP.Net web application. The application sends a postcode (similar to Zip code) to google which returns information relating to the location via Json. The application then uses the information to compare the distance with other locations which it has Geolocation data for on file.

The problem I'm having is that when I'm trying to request the Json data from the application I've recently started getting an exception "No connection could be made because the target machine actively refused it ...". I'm confused as the function was previously working although I haverecently moved the computer between offices so its on a new network point if that's relevant.

This is the code (the location is a class which stores information related to the location that's being investigated, an example postcode would be 'M13 9WL':

using (WebClient wc = new WebClient())
        {
            string SearchString = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location.Postcode + "&key=AIzaSyAj0ZqfytaSX2B_Nm9MXRR63AL3uqWRgx4";
            var json = wc.DownloadString(SearchString);
            dynamic data = JObject.Parse(json);
            location.Latitude = data.results[0].geometry.location.lat;
            location.Longitude = data.results[0].geometry.location.lng;

        }

The exception occurs on the second line of code with the message "Unable to connect to the remote server" and inner exception message "No connection could be made because the target machine actively refused it XXX.XX.XXX.XXX:XXX"

When I run the same URL through the browser it works fine: https://maps.googleapis.com/maps/api/geocode/json?address=M13%209WL&key=AIzaSyAj0ZqfytaSX2B_Nm9MXRR63AL3uqWRgx4

Not sure what the problem is as the code did previously work. Any advice would be appreciated.

Error retrieving token ASP.NET Web API template

$
0
0

I’m working with a project that has been created as a ASP.Net Web Application with the ‘Web API’ template and ‘Individual User Accounts’ enabled as the authentication option. I have a console application that consumes the web api. But When I want to get the token it gives me an html string with 404 not found in stead of a json array. What am I doing wrong?

This is mij console app code:

using ConsoleApplication1.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
{
    const string userName = "user@user.com";
    const string password = "Password01!";
    const string apiBaseUri = "http://localhost/WebAPITest";
    const string apiGetPeoplePath = "/api/people";

    static void Main(string[] args)
    {
        //Get the token
        var token = GetAPIToken(userName, password, apiBaseUri).Result;
        Console.WriteLine("Token: {0}", token);

        //Make the call
        var response = GetRequest(token, apiBaseUri, apiGetPeoplePath).Result;
        Console.WriteLine("response: {0}", response);

        //wait for key press to exit
        Console.ReadKey();
    }

    private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
    {
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //setup login data
            var formContent = new FormUrlEncodedContent(new[]
            {
 new KeyValuePair<string, string>("grant_type", "password"),
 new KeyValuePair<string, string>("username", userName),
 new KeyValuePair<string, string>("password", password),
 });

            //send request
            HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);

            //get access token from response body
            var responseJson = await responseMessage.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseJson);
            return jObject.GetValue("access_token").ToString();
        }
    }

    static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
    {
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            //make request
            HttpResponseMessage response = await client.GetAsync(requestPath);
            var responseString = await response.Content.ReadAsStringAsync();
            return responseString;
        }
    }
}

}



Am I missing something? 

OAuth2.scopes -> AuthorizeAttribute for all controllers

$
0
0

Hi,

I want to implement OAuth2 authentication scopes.

I have 5 controllers. I added one XXXAutorizeAttribute filter to project and [XXXAuthorize("Controller1.Read")] added in every controller .

  1. Is it normal for the first request to webapi to call XXXAutorizeAttribute contructor 5*2 times? Why?
  2. How can I get e.g. Controller1.Read in XXXAutorizeAttribute.IsAuthorized() method? If I set a property in XXXAutorizeAttribute class I have only last value from 5*2 calls. 

What template options do I use to create a Web API that has the calls listed on the API page?

$
0
0

I created this a couple of years ago for another client, but I can't remember what options I had created.

There is a menu option for API created and it lists the Web API methods in the solution.

I tried creating an empty project with Web API selected, but it did not create the menu or an Asp.Net project.

Thanks

Need help upgrading my Project

$
0
0

Hello,

I started a WEB API project with Visual Studio 2015 last year in June 2015. Since then the project has grown to be pretty massive and is currently being used in production serving clients. The biggest fear I currently have about the project is the fact that it is becoming out of date and we are having a difficult time upgrading the dependencies, and adding new "WCF Services" (SOAP APIs).

The biggest issue with upgrading is confusion on what is the greatest and latest framework to use. In addition, with our "telerik", "force" and "chargify" dependencies being essential for our business we want to upgrade without breaking them. When using .net core the don't seem to work with the project because they are dependent on .net. 

This is our "project.json" file.

{"webroot": "wwwroot","version": "1.0.0-*","dependencies": {"Microsoft.AspNet.Mvc": "6.0.0-beta5","Microsoft.AspNet.Server.IIS": "1.0.0-beta5","Microsoft.AspNet.Server.WebListener": "1.0.0-beta5","Microsoft.AspNet.StaticFiles": "1.0.0-beta5","System.Data.SqlClient": "4.0.0-beta-22816","System.IO.FileSystem": "4.0.0-beta-22816","System.ServiceModel": "1.0.0","Microsoft.Net.Http": "2.2.29","telerik.reporting": "9.2.15.1105","DeveloperForce.Force": "1.3.0","chargify": "1.1.5967.40624"
  },"commands": {"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
  },"frameworks": {"dnx451": {"frameworkAssemblies": {"System.Runtime.Serialization": "4.0.0.0","System.ServiceModel": "4.0.0.0"
      }
    }
  },"exclude": ["wwwroot","node_modules","bower_components"
  ],"publishExclude": ["node_modules","bower_components","**.xproj","**.user","**.vspscc"
  ]
}


I would greatly appreciate any help/guidance on what to do with our project at this point. With all the new Microsoft tech coming out of beta we would like to be on the right path for long term support. 

Thank You!


I have two controllers with API methods, only one shows up in discovery

$
0
0

I added a controller, and both have Web API methods.

I even copied this controller from another project that has the discovery working (when you click API, all the methods and url's are shown).

But for some reason in my new project, the discovery doesn't show the class I want.

Is there something I have to do to make this discovery work?

The default ValuesController works, but my custom controller that only has 1 method for now doesn't show.

The controller class is here:

  public class TestOpAPIController : ApiController
    {
        #region Methods
            #region GetClients()
            /// <summary>
            /// method Get Clients
            /// </summary>
            [Route("GetClients")]
            [HttpGet]
            public static List<Client> GetClients()
            {
                // initial value
                List<Client> clients = new List<Client>();
                // Create a context
                WebDbContext context = new WebDbContext();
                // load the companies
                List<Company> companies = context.Company.ToList();
                // convert the Companies to Client objects
                clients = Convert(companies);
                // return value
                return clients;
            }
            #endregion

        #endregion

connect to a company who has a Web API

$
0
0

All my search results show how to create a Web API and that is not what I want.

I want to connect to a company who has a Web API. What are the basic steps to create a console application C# framework 4.5.2 to connect to get Authentication for their API methods based on the inclusion of a "Bearer" token in the standard "Authorization" header of any HTTP requests. Token is in JSON Web Token (JWT) format, and token can be retrieved though standard authentication methods.

Also basic steps to call that companies API methods, so I can upload a JSON file.

Thank you

xamarin forms, own web api, oauth2

$
0
0

Hi, 

I'm no expert so please write your answer kindly and simply.

I have xamarin forms app, i have own asp.net core web api. What i want to achieve is to access this webapi using some oauth2 provider (google, facebook or my own - is it possible?).

What way is mostly preferred in these days?  What is the most easy way? 

Thank you

Web API endpoints stops responding when a file upload is going on

$
0
0

Hi,

I am facing the following issue. I have implemented a application with Web Api 2. One of the endpoints accepts multipart which I use for uploading file. After I start upload until it completes all other api endpoints are not responding. Once the file is received in the server or if I cancel the upload then the rest of the api end points starts responding.

This is hosted in Azure App Service. I am unable to find whats causing this. Can you guys help me out on this ?

how to consume wcf

$
0
0

Hi Friends,

I have created a wcf application in localhost that I have consume in my ASP.NET application. that is working fine.

 I have hosted it in my windows server (IIS7) and browse that, and it is working http://IP:82/IqaScheduledServices.svc

but when i consume it in my application. it says : 

An error (Details) occurred while attempting to find services at http://IP:82/IqaScheduledServices.svc

Please Help

Viewing all 4850 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>